﻿var g_openFile;
var baseDataPanel;
var bizPackPanel;
var cminput_modal;
var basedata_modal;
var toptop_modal;

var objn = {name: 'xz', age: 232};
var cellDgnEvent = {
  onSelChange: function (obj, info) {
    this.updateFontStyle();
    this.updateFontName();
    this.updateColor();
    this.updateSetting();
  },
  onChange: function (obj, info) {

  },
  onCellDoubleClick: function (obj, info) {
    var cellP = cn.getCurCellPlus();
    var tag = cn.getCurCellPlus().selection().tag();
    if (tag && tag.indexOf("cus:bsd") >= 0) {
      var bd = cm.strSplit(tag, ":");
      var ret = yddser.getGroupBaseData(bd[2], bd[3], 1);
      if (cm.dataOk(ret)) {
        cn.getCurCellPlus().selection().cellType(new JsTreeCellType(ret.data));
      }
      else {
        cm.myAlert(ret.msg);
      }
    }
  },
  onLeaveCell: function (obj, info) {

  },
  setDgFont: function (fontStr) {
    var fontname = cm.getFontName(fontStr);
    var fontsize = cm.getFontSize(fontStr);
    var span = '<span class="am-icon-caret-down"><span>';
    $('#J-font-family').html(fontname + span);
    $('#J-font-size').html(fontsize + span);
  },
  setDgColor: function (fclr, bclr) {
    $('#J-font-color').css("color", fclr == null ? "gray" : fclr);
    $('#J-bg-color').css("color", bclr == null ? "gray" : bclr);
  },
  setDgFontStyle: function (str) {
    var fontStyle = cm.getFontStyle(str);
    var fontBold = cm.getFontBold(str);
    if (cm.strIsNotEmpty(fontBold) && fontBold == 'bold') {
      $('#J-font-bold').parent().addClass('on');
    }
    else {
      $('#J-font-bold').parent().removeClass('on');
    }

    if (cm.strIsNotEmpty(fontStyle) && fontStyle == 'italic') {
      $('#J-font-italic').parent().addClass('on');
    }
    else {
      $('#J-font-italic').parent().removeClass('on');
    }
  },
  setDgWordWrap: function (v) {
    if (v) {
      $('.J-multi-line').parent().addClass('on');
    }
    else {
      $('.J-multi-line').parent().removeClass('on');
    }
  },
  setDgFontDecorate: function (v) {
    $('#J-font-underline').parent().removeClass('on');
    $('#J-font-through').parent().removeClass('on');
    if ((v & GcSpread.Sheets.TextDecorationType.LineThrough) == GcSpread.Sheets.TextDecorationType.LineThrough) {
      $('#J-font-through').parent().addClass('on');
    }
    if ((v & GcSpread.Sheets.TextDecorationType.Underline) == GcSpread.Sheets.TextDecorationType.Underline) {
      $('#J-font-underline').parent().addClass('on');
    }
  },
  setClFontName: function (str) {
    var cellP = cn.getCurCellPlus();
    cellP.selection().font(str);
  },
  setClFontSize: function (str) {
    var cellP = cn.getCurCellPlus();
    cellP.selection().font(null, str);
  },
  setClFontBold: function () {
    var cellP = cn.getCurCellPlus();
    var str = cellP.selection().font();
    str = cm.getFontBold(str);
    if (cm.strIsNotEmpty(str) && str == 'bold') {
      cellP.selection().font(null, null, 'normal');
    }
    else {
      cellP.selection().font(null, null, 'bold');
    }
  },
  setClWordWrap: function () {
    var cellP = cn.getCurCellPlus();
    var h = $('.J-multi-line').parent().hasClass('on');
    if (h) {
      cellP.selection().wordWrap(false);
    }
    else {
      cellP.selection().wordWrap(true);
    }
  },
  updateFontStyle: function () {
    var cell = cn.getCurCellPlus();
    var fontstr = cell.selection().font();
    this.setDgFontStyle(fontstr);
    var v = cell.selection().textDecoration();
    this.setDgFontDecorate(v);
    v = cell.selection().wordWrap();
    this.setDgWordWrap(v);
  },
  updateFontName: function () {
    var cell = cn.getCurCellPlus();
    var fontstr = cell.selection().font();
    this.setDgFont(fontstr);
  },
  updateColor: function () {
    var cell = cn.getCurCellPlus();
    var fclr = cell.selection().foreColor();
    var bclr = cell.selection().backColor();
    this.setDgColor(fclr, bclr);
  },
  updateSetting: function () {
    var cellP = cn.getCurCellPlus();

    var tab = cellP.tabStripVisible();
    var rv = cellP.currentSheet2().rowHeaderVisible();
    var cv = cellP.currentSheet2().colHeaderVisible();
    var newT = cellP.newTabVisible();

    if (tab)
      $('.J-setting-tab').parent().addClass('on');
    else
      $('.J-setting-tab').parent().removeClass('on');

    if (rv)
      $('.J-setting-rowheaderV').parent().addClass('on');
    else
      $('.J-setting-rowheaderV').parent().removeClass('on');

    if (cv)
      $('.J-setting-colheaderV').parent().addClass('on');
    else
      $('.J-setting-colheaderV').parent().removeClass('on');

    if (newT)
      $('.J-setting-new').parent().addClass('on');
    else
      $('.J-setting-new').parent().removeClass('on');

    var fill = cellP.canUserDragDrop();
    if (fill) {
      $('.J-setting-dragfill').parent().addClass('on');
    } else {
      $('.J-setting-dragfill').parent().removeClass('on');
    }
  },
  getCurCell: function () {
    return cn.getCurCellPlus();
  },
  colorPickChange: function (type, color) {
    var cell = cn.getCurCellPlus();
    if (type == 1) {
      cell.selection().foreColor(color.toHexString());
    }
    else if (type == 2) {
      cell.selection().backColor(color.toHexString());
    }
    this.updateColor();
  },
  colorPickHide: function (type, color) {

  },
  colorPickConfirm: function (type, color) {

  },
  colorPickCancel: function (type, color) {

  },
  openForm: function (e, data) {
    var cpl = cn.openForm(e, data);
    cn.setCplFormTableArrPos(cpl, null, null);
  }
};
cm.forEachKeys(objn, function (obj, key) {
  if (key == 'name') {
    cm.makeCmInputObj(obj, key, "名称:", 1);
  }
  else if (key == 'age') {
    cm.makeCmInputObj(obj, key, '年龄:', 1);
  }
});

$(function () {
  Vue.component('cminput-comp', {
    template: '#cminput-template',
    props: {items: Array},
    data: function () {
      return {'newData': []};
    },
    methods: {
      //修改成员信息
      edit: function (u) {
      },
      delete: function (u) {
      },
      deleteSelected: function () {
      },
      prevent: function () {
        this.valid = true;
      }
    },
    computed: {
      newData2: {
        get: function () {
          return cm.cloneObj(this.newData);
        },
        set: function (v) {
          var dd = v;
        }
      }
    },
    watch: {
      newData: function (val, oldVal) {
        console.log('new: %s, old: %s', val, oldVal)
      },
      items: function (val, oldVal) {
        this.newData = this.items;
      },
      deep: true
    }
  });

  cminput_modal = new Vue({
    el: '#cminput-modal',
    data: {
      editData: {vm_arr: []},
      func: {},
      cancelF: {}
    },
    methods: {
      cancel: function (u) {
        this.cancelF && this.cancelF(this.editData);
      },
      save: function (u) {
        this.func && this.func(this.editData);
      },
      showModal: function (func, cancelF) {
        this.func = func;
        this.cancelF = cancelF;
        $("#cminput-modal").modal();
      },
      clear: function () {
        this.editData = {};
        this.func = {};
      }
    }
  });

  basedata_modal = new Vue({
    el: '#basedata-modal',
    data: {
      data: {},
      title: "",
      editFor: 1,
      funcOk: {},
      funcCancel: {}
    },
    methods: {
      cancel: function (u) {
        this.funcCancel && this.funcCancel(this.data);
      },
      save: function (u) {
        this.funcOk && this.funcOk(this.data);
      },
      showModal: function (title, v, funcOk, funcCancel) {
        this.title = title;
        this.editFor = v;
        this.funcOk = funcOk;
        this.funcCancel = funcCancel;
        $("#basedata-modal").modal();
      },
      showTreeDrop: function () {
        var vdata = this.data;
        toptop_modal.showModal("选择父对象", 1, function (data) {
          vdata.parentText = data.itemText;
          vdata.parentId = data.itemId;
        });
      },
      clear: function () {
        this.title = "";
        this.editFor = 0;
        this.data = {};
        this.funcOk = {};
      }
    }
  });

  toptop_modal = new Vue({
    el: '#toptop-modal',
    data: {
      data: {},
      title: "",
      editFor: 1,
      funcOk: {},
      funcCancel: {}
    },
    methods: {
      cancel: function (u) {
        this.funcCancel && this.funcCancel(this.data);
        this.clear();
      },
      save: function (u) {
        if (this.editFor == 1) {
          var selNode = $('#toptop-treedata').jstree(true).get_selected(true);
          this.data = selNode[0].original;
        }
        this.funcOk && this.funcOk(this.data);
        this.clear();
      },
      showModal: function (title, v, funcOk, funcCancel) {
        this.title = title;
        this.editFor = v;
        this.funcOk = funcOk;
        this.funcCancel = funcCancel;

        if (v == 1) {
          var CurrentNode = $('#jstree-basedata').jstree(true).get_selected(true);
          if (cm.isEmptyArr(CurrentNode)) {
            cn.showFailedDlg("请选择基础数据项");
            return;
          }

          var retData = yddser.getGroupBaseData(CurrentNode[0].original.groupName, CurrentNode[0].original.dataShowType, 1);
          if (cm.dataNotOk(retData)) {
            cn.showFailedDlg(retData.msg);
            return;
          }
          cm.setTreeEachItem(retData.data, "children", function (obj) {
            obj.text = obj.itemText;
            obj.id = obj.oid;
          });

          var ref = $('#toptop-treedata').jstree(true);
          if (ref) {
            ref.destroy();
          }
          $('#toptop-treedata').jstree({
            'core': {
              'multiple': true,
              "check_callback": true,
              'data': retData.data,
            },
            "types": {
              "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
              "root": {"icon": "../main/img/folder.png", "valid_children": ["default"]},
              "default": {"valid_children": ["default", "file"]},
              "file": {"icon": "../main/img/file.png", "valid_children": []}
            },
            "plugins": ["dnd", "search", "state", "types", "wholerow"]
          }).bind("select_node.jstree", function (e, data, event) {
          });
        }
        $("#toptop-modal").modal();
      },
      showTreeDrop: function () {
        var $dropdown = $("#preview-dropdown-jstree");
        $dropdown.dropdown('open');
        this.data.parentText = "testtest";
        this.data.parentId = "testtest";
      },
      clear: function () {
        this.title = "";
        this.editFor = 0;
        this.data = {};
        this.funcOk = {};
      }
    }
  });

});

var user = {};
$(document).ready(function () {
  var buttonCell = new Vue({
    el: '#buttonCellModal',
    data: {
      backColor: '#FDFDFD',
      buttonText: 'button'
    },
    methods: {}
  });
  var autocodeModal = new Vue({
    el: '#autocode-modal',
    data: {
      func: {},
      codeRule: {},
      demoData: [],
      title: "添加自动编码"
    },
    methods: {
      showModal: function (code, func) {
        if (code) {
          var ret = yddser.getCode(code);
          if (cm.dataNotOk(ret)) {
            cn.showFailedDlg(ret.msg);
            return;
          }
          this.title = "修改自动编码";
          this.codeRule = ret.data;
        }
        else {
          this.title = "添加自动编码";
          this.codeRule = yddser.createObj("cd", false);
        }
        this.demoData = yddser.getDemoCode(this.codeRule).data;
        this.func = func;
        $("#autocode-modal").modal();
      },
      confirm: function () {
        this.func(this.codeRule);
      },
      cancel: function () {
        this.clear();
      },
      getDemoData: function () {
        this.demoData = yddser.getDemoCode(this.codeRule).data;
      },
      clear: function () {
        this.title = "添加自动编码";
        this.codeRule = {};
        this.demoData = [];
      }
    },
    watch: {
      'codeRule.codePrefix': function (val) {
        this.getDemoData();
      },
      'codeRule.codeDataFmt': function (val) {
        this.getDemoData();
      }
    }
  });

  $('#basedata-dropdown-sel').on('open.dropdown.amui', function (e) {
    var retData = yddser.getAllGroupBaseData();
    bizPackPanel.$data.baseData = retData.data;
  });

  g_openFile = new Vue({
    el: '#my-localFile',
    data: {
      callBack: {},
      reader: new FileReader()
    },
    methods: {
      cancel: function () {
        this.stop = 1;
        $('#my-localFile').modal('close');
      },
      confirm: function () {
        var files = $('input[name="test"]').prop('files');//获取到文件列表
        if (files.length == 0) {
          alert('请选择文件');
        } else {
          this.reader.readAsText(files[0], "UTF-8");//读取文件
          var openDlg = this;
          this.reader.onload = function (evt) { //读取完文件之后会回来这里
            if (openDlg.stop == null) {
              openDlg.callBack(evt.target.result);
            }
            $('#my-alert').modal('close');
          };
          cn.showFailedDlg2("请稍后.....", function (inData) {
            $('#my-alert').modal('close');
            inData.stop = 1;
          });
        }
        $('#my-localFile').modal('close');
      }

    }
  });
  var checkboxCell = new Vue({
    el: '#checkboxCellModal',
    data: {
      checkboxFalse: '未选择',
      checkboxTrue: '已选择',
    },
    methods: {}
  });
  var comboCell = new Vue({
    el: '#comboCellModal',
    data: {
      items: "item1,item2,item3"
    },
    methods: {}
  });
  $("#button-color").spectrum({
    allowEmpty: true,
    color: "#ECC",
    showInput: true,
    containerClassName: "full-spectrum",
    showInitial: true,
    showPalette: true,
    showSelectionPalette: true,
    showAlpha: true,
    maxPaletteSize: 10,
    preferredFormat: "hex",
    localStorageKey: "spectrum.demo",
    move: function (color) {

    },
    show: function () {

    },
    beforeShow: function () {

    },
    hide: function (color) {

    },
    change: function (color) {
      $('#button-color').css('background-color', color);
      buttonCell.$data.backColor = color;
    },

    palette: [
      ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", /*"rgb(153, 153, 153)","rgb(183, 183, 183)",*/
        "rgb(204, 204, 204)", "rgb(217, 217, 217)", /*"rgb(239, 239, 239)", "rgb(243, 243, 243)",*/ "rgb(255, 255, 255)"],
      ["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
        "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
      ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
        "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
        "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
        "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
        "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
        "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
        "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
        "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
        /*"rgb(133, 32, 12)", "rgb(153, 0, 0)", "rgb(180, 95, 6)", "rgb(191, 144, 0)", "rgb(56, 118, 29)",
         "rgb(19, 79, 92)", "rgb(17, 85, 204)", "rgb(11, 83, 148)", "rgb(53, 28, 117)", "rgb(116, 27, 71)",*/
        "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
        "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
    ]
  });

  var userPanel = null;

  function reloadUserPackForm() {
    $('#userright-pack-tree').jstree({
      'core': {
        'multiple': true,
        'check_callback': true,
        'data': yddser.getPackList().data
      },
      'checkbox': {
        tie_selection: false,
        three_state: false,
        whole_node: false
      },
      'search': {
        show_only_matches: true
      },
      'plugins': ['checkbox', 'wholerow', "types", 'search'],
      "types": {
        "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
        "root": {"icon": "../main/img/folder.png", "valid_children": ["default", "file"]},
        "default": {"valid_children": ["default", "file"]},
        "file": {"icon": "../main/img/file.png", "valid_children": []}
      },
    }).on('check_node.jstree', function (node, ele) {
      var $userrightpack = $('#userright-pack-tree');
      $userrightpack.jstree(true).deselect_all();
      $userrightpack.jstree(true).select_node(ele.node.original.oid);

      var deptUserId = getUserRightDeptUserId();
      var selNode = $userrightpack.jstree(true).get_selected();
      var packFormId = selNode[0];

      // if (userAuthority.$data.curModify.data[deptUserId] == null) {
      //   userAuthority.$data.curModify.data[deptUserId] = {};
      // }
      // if (userAuthority.$data.curModify.data[deptUserId][packFormId] == null) {
      //   userAuthority.$data.curModify.data[deptUserId][packFormId] = {};
      // }

    }).on('select_node.jstree', function (node, ele) {
      var deptUserId = getUserRightDeptUserId();
      var packFormId = ele.node.original.oid;
      var right = yddser.getRightByUserForm(deptUserId, packFormId).data;
      if (right.rightVal != null) {
        userAuthority.$data.curRightInfo.view = right.view;
        userAuthority.$data.curRightInfo.edit = right.edit;
        if (!right.self) {
          userAuthority.$data.curRightInfo.rightFrom = right.deptName;
        }
        else {
          userAuthority.$data.curRightInfo.rightFrom = "无继承";
        }
      }
      else {
        userAuthority.$data.curRightInfo.view = false;
        userAuthority.$data.curRightInfo.edit = false;
        userAuthority.$data.curRightInfo.rightFrom = "";
      }
    }).on('uncheck_node.jstree', function (node, ele) {

      // var deptUserId = getUserRightDeptUserId();
      // userAuthority.$data.curModify.modify = true;
      // var $da = userAuthority.$data;
      // delete $da.curModify.data[deptUserId][ele.node.original.oid];
      // userAuthority.$data.curRightInfo.view = false;
      // userAuthority.$data.curRightInfo.edit = false;
      // userAuthority.$data.curRightInfo.rightFrom = "";

    }).on('hover_node.jstree', function (node, ele) {
      var setOptions = function() {
        btPop.$data.nodeId = ele.node.id;
        btPop.$data.curNode = ele.node;
        btPop.$data.userId = getUserRightDeptUserId();
        btPop.$data.jstree = 'userright-pack-tree';
        btPop.disableReset = Math.random() > 0.5;
        authCom.$data.nodeId = ele.node.id;
        authCom.$data.view = true;
        authCom.$data.fillIn = false;
      };
      addSettings('#userright-pack-tree', ele, setOptions);
    });
  }
  function reloadUserDeptTree() {
    var retData = yddser.getDept("all");
    if (cm.dataNotOk(retData)) {
      return;
    }
    cm.setTreeEachItem(retData.data, "children", function (obj) {
      obj.id = obj.oid;
      obj.text = obj.deptName;
      obj.type = 'department';
    });

    $('#user-dept-tree').data('jstree', false).empty();
    $('#user-dept-tree').jstree({
      'core': {
        "check_callback": true,
        'force_text': true,
        'data': retData.data,
      },
      "types": {
        "#": {
          "max_children": 1,
          "max_depth": 4,
          "valid_children": ["company", "department", "file"]
        },
        "department": {
          "icon": "../main/img/department.png",
          "valid_children": ["default", "file", "department"]
        },
        "default": {"valid_children": ["default", "file", "department"]},
        "company": {"icon": "../main/img/company.png", "valid_children": ["department"]}
      },
      "plugins": ["dnd", "search", "state", "types", "wholerow"]

    }).on('hover_node.jstree', function (node, ele) {
      var setOptions = function() {
        btPop.$data.nodeId = ele.node.id;
        btPop.$data.curNode = ele.node;
        btPop.$data.jstree = 'user-dept-tree';
      }
      addSettings('#user-dept-tree', ele, setOptions);
    }).on("select_node.jstree", function (e, data) {
      var users = cn.openDeptUser(e, data);
      userPanel.$data.showGrid = true;
      userPanel.$data.gridColumns = [
        {name: 'userName', label: '姓名', search: false},
        {name: 'gender', label: '性别', search: false},
        {name: 'cellphone', label: '电话', search: false},
        {name: 'email', label: '邮箱', search: false},
        {name: 'userType', label: '用户类型', search: false}
      ];
      for(var i = 0; i < users.data.length; i++) {
        users.data[i].show = true;
      }
      userPanel.$data.gridData = users.data;
    })
  }

  var disableAllRepSelEvent = false;
  function reloadRightTree() {
    var retData = yddser.getRight("all", true);
    if (cm.dataNotOk(retData)) {
      return;
    }

    $('#job-position').data('jstree', false).empty();
    $('#job-position').jstree({
      'core': {
        'multiple': false,
        'check_callback': true,
        'data': retData.data,
      },
      "types": {
        "#": {"max_children": 1, "max_depth": 4, "valid_children": ["company", "department"]},
        "department": {"icon": "../main/img/department.png", "valid_children": ["default"]},
        "default": {"valid_children": ["default", "file"]},
        "company": {"icon": "../main/img/company.png", "valid_children": ["department"]},
      },
      "plugins": ["types", "wholerow"]
    }).on("select_node.jstree", function (e, data) {
      disableAllRepSelEvent = true;
      $('#all-reports').jstree(true).deselect_all();
      var ret = yddser.getRightToPackForm(data.node.original.oid);
      var ret2 = yddser.getRightToDeptUser(data.node.original.oid);
      if (cm.dataNotOk(ret) || cm.dataNotOk(ret2)) {
        cn.showFailedDlg(ret.msg);
        return;
      }
      disableAllRepSelEvent = true;
      $('#all-reports').jstree(true).select_node(ret.data);

    });
  }

  function reloadRightPackTree() {
    var retData = yddser.getPackList();
    $('#all-reports').data('jstree', false).empty();
    $('#all-reports').jstree({
      'core': {
        'multiple': true,
        "check_callback": true,
        'data': retData.data,
      },
      "types": {
        "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
        "root": {"icon": "../main/img/folder.png", "valid_children": ["default"]},
        "default": {"valid_children": ["default", "file"]},
        "file": {"icon": "../main/img/file.png", "valid_children": []}
      },
      'checkbox': {
        // three_state: false
      },
      "plugins": ["dnd", "search", "state", "types", "wholerow", "checkbox"]
    }).bind("select_node.jstree", function (e, data, event) {
      if (disableAllRepSelEvent) {
        disableAllRepSelEvent = false;
        return;
      }
      var CurrentNode = $('#job-position').jstree(true).get_selected(true);
      var rightKV = [];
      rightKV.push({rightId: CurrentNode[0].original.oid, packFormId: data.node.original.oid});
      var ret = yddser.addRightToPackForm(rightKV);
      if (cm.dataNotOk(ret)) {
        disableAllRepSelEvent = true;
        $('#all-reports').jstree(true).deselect_node(data.node.original.oid, true);
      }

    }).bind("deselect_node.jstree.jstree", function (e, data, event) {
      if (disableAllRepSelEvent) {
        disableAllRepSelEvent = false;
        return;
      }
      var CurrentNode = $('#job-position').jstree(true).get_selected(true);
      var rightKV = [];
      rightKV.push({rightId: CurrentNode[0].original.oid, packFormId: data.node.original.oid});
      var ret = yddser.delRightToPackFormKV(rightKV);
      if (cm.dataNotOk(ret)) {
        disableAllRepSelEvent = true;
        $('#all-reports').jstree(true).select_node(data.node.original.oid, true);
      }
    })
  }

  function reloadBaseDataTree() {
    var retData = yddser.getAllGroupBaseData();
    if (cm.dataNotOk(retData)) {
      cn.showFailedDlg(retData.msg);
      return;
    }
    $('#jstree-basedata').data('jstree', false).empty();
    $('#jstree-basedata').on('hover_node.jstree', function (node, ele) {
      var setOptions = function() {
        btPop.$data.nodeId = ele.node.id;
        btPop.$data.curNode = ele.node;
        btPop.$data.jstree = 'basedata';
      }
      addSettings('#jstree-basedata', ele, setOptions);
    }).jstree({
      'core': {
        'multiple': true,
        "check_callback": true,
        'data': retData.data,
      },
      "types": {
        "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
        "root": {"icon": "../main/img/folder.png", "valid_children": ["default"]},
        "default": {"valid_children": ["default", "file"]},
        "file": {"icon": "../main/img/file.png", "valid_children": []}
      },
      "plugins": ["dnd", "search", "state", "types", "wholerow"]
    }).bind("select_node.jstree", function (e, data, event) {
      baseDataPanel.setPanelData(data.node.original.groupName, data.node.original.dataShowType);
    })
  }

  var user = yddser.getCurUser();
  $('#span-curuser-name').html(user.data.userName);

  var userLoaded = false;
  $("#nav-users").click(function (e) {
    $(this).addClass('navigator-bar-focus');
    $(this).siblings().removeClass('navigator-bar-focus');
    $('#box > .module').removeClass('active');
    $('#user-panel').addClass('active');

    if (!userLoaded) {
      userPanel = new Vue({
        el: '#user-panel',
        data: {
          showGrid: false,
          gridColumns: [],
          gridData: [],
          userInfo: {},
          searchkey: ''
        },
        methods: {
          edit: function (u) {

          },
          delete: function (u) {
          },
          deleteSelected: function (selectIds) {
            cm.myAlertFunc("确定要删除这些用户吗?", this.$refs.users, function (users) {
              var ret = yddser.delUser(users.userIds.join(","));
              if ( cm.dataOk(ret) ){
                cm.arrDelByArr(userPanel.gridData, users.userIds,function (s, d) {
                  if (s.oid==d){
                    return 0;
                  }
                  return 1;
                });
              }
            });
          },
          search: function () {
            var searchOptions = [];
            var i = 0;
            for (i = 0; i < this.gridColumns.length; i++) {
              if (this.gridColumns[i].search) {
                searchOptions.push(this.gridColumns[i].name);
              }
            }
            if (this.searchkey != '' && searchOptions.length > 0) {
              for (i = 0; i < this.gridData.length; i++) {
                var item = this.gridData[i];
                item.show = false;
                for (var j = 0; j < searchOptions.length; j++) {
                  var fv = this.gridData[i][searchOptions[j]];
                  if (fv != null && fv.indexOf(this.searchkey) != -1) {
                    item.show = true;
                    break;
                  }
                }
                this.gridData.splice(i, 1, item);
              }
            }
          },
          toggleSearchOption: function (col) {
            col.search = !col.search;
          }
        }
      });

      reloadUserDeptTree();
      reloadRightTree();
      reloadRightPackTree();
      reloadUserPackForm();

      // init serach-bar
      new Vue({
        el: '#company-serach-bar'
      });

      userLoaded = true;
    }
  });

  $('#nav-basedata').click(function () {
    if (baseDataPanel == null) {
      baseDataPanel = new Vue({
        el: '#base-data',
        data: {
          init: false,
          gridData: [],
          gridColumns: []
        },
        methods: {
          save: function () {

          },
          load: function () {

          },
          setPanelData: function (groupName, showType) {
            var ret = yddser.getGroupBaseData(groupName, showType, 0);
            if (cm.dataNotOk(ret)) {
              cn.showFailedDlg(ret.msg);
              return;
            }
            this.gridColumns = [
              {name: 'itemText', label: '显示名称'},
              {name: 'itemId', label: '数据值'},
              {name: 'groupName', label: '分组名称'},
              {name: 'parentId', label: '父对象'},
              {name: 'createTimeStr', label: '创建时间'},
              {name: 'updateTimeStr', label: '更新时间'},
              {name: 'ext1', label: '扩展1'}
            ];
            cm.setObjDateStr(ret.data, "createTime", "updateTime");
            for(var i = 0; i < ret.data.length; i++) {
              ret.data[i].show = true;
            }
            this.gridData = ret.data;
          },
          createNew: function () {
            basedata_modal.$data.data = yddser.createObj("bsd", false);
            basedata_modal.$data.data.itemId = "itemId";
            basedata_modal.$data.data.itemText = "itemText";
            basedata_modal.showModal("新增基础数据", 1, function (editData) {
              var ret = yddser.addOrUpdBaseDataItem(editData);
              if (cm.dataNotOk(ret)) {
                cn.showFailedDlg(ret.msg);
                return;
              }
              var $ref = $('#jstree-basedata').jstree(true);
              editData.id = editData.oid;
              editData.text = editData.groupName;
              editData.type = 'root';
              editData.createTime = cm.dtToLong();
              editData.updateTime = editData.createTime;
              editData.updateTimeStr = cm.dtToLYMDMS(editData.updateTime);
              editData.createTimeStr = cm.dtToLYMDMS(editData.createTime);
              var ddd = $ref.create_node("#", editData, 'first');
              baseDataPanel.$data.gridData.push(editData);
            });
          },
          deleteSelected: function () {
            cm.myAlertFunc("确定要删除这些数据项吗?", this.$refs.basedatas, function (users) {
              var ret = yddser.deleteBaseDataItem(users.userIds.join(","));
              if ( cm.dataOk(ret) ){
                cm.arrDelByArr(baseDataPanel.gridData, users.userIds,function (s, d) {
                  if (s.oid==d){
                    return 0;
                  }
                  return 1;
                });
              }
            });
          },
          createNewItem: function () {
            var CurrentNode = $('#jstree-basedata').jstree(true).get_selected(true);
            if (cm.isEmptyArr(CurrentNode)) {
              cn.showFailedDlg("请选择基础数据项");
              return;
            }

            basedata_modal.$data.data = yddser.createObj("bsd", false);
            basedata_modal.$data.data.groupName = CurrentNode[0].original.groupName;
            basedata_modal.$data.data.dataShowType = CurrentNode[0].original.dataShowType;
            basedata_modal.showModal("新建数据项", 2, function (editData) {
              editData.createTime = cm.dtToLong();
              editData.updateTime = editData.createTime;
              editData.updateTimeStr = cm.dtToLYMDMS(editData.updateTime);
              editData.createTimeStr = cm.dtToLYMDMS(editData.createTime);
              editData.show=true;
              var ret = yddser.addOrUpdBaseDataItem(editData);
              if (cm.dataNotOk(ret)) {
                cn.showFailedDlg(ret.msg);
                return;
              }
              var $ref = $('#jstree-basedata').jstree(true);
              var ddd = $ref.create_node("#", {
                id: editData.groupName,
                text: editData.groupName
              }, 'first');
              baseDataPanel.$data.gridData.push(editData);
            });
          },
          dropDwon: function () {
            var CurrentNode = $('#jstree-basedata').jstree(true).get_selected(true);
            if (cm.isEmptyArr(CurrentNode)) {
              cn.showFailedDlg("请选择基础数据项");
              return;
            }
            var genTree = CurrentNode[0].original.dataShowType == 2 ? 1 : 0;
            var ret = yddser.getGroupBaseData(CurrentNode[0].original.groupName, CurrentNode[0].original.dataShowType, genTree);
            if (cm.dataNotOk(ret)) {
              cn.showFailedDlg(ret.msg);
              return;
            }

            var ref = $('#preview-treedata').jstree(true);
            if (ref) {
              ref.destroy();
            }
            $('#preview-treedata').jstree({
              'core': {
                'multiple': true,
                "check_callback": true,
                'data': ret.data,
              },
              "types": {
                "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
                "root": {"icon": "../main/img/folder.png", "valid_children": ["default"]},
                "default": {"valid_children": ["default", "file"]},
                "file": {"icon": "../main/img/file.png", "valid_children": []}
              },
              "plugins": ["dnd", "search", "state", "types", "wholerow"]
            }).bind("select_node.jstree", function (e, data, event) {
            });

            var $dropdown = $("#preview-dropdown-jstree");
            $dropdown.dropdown('open');
          },
          preview: function () {

          }
        }
      });
    }

    $(this).addClass('navigator-bar-focus');
    $(this).siblings().removeClass('navigator-bar-focus');
    $('#box > .module').removeClass('active');
    $('#base-data').addClass('active');

    if (!baseDataPanel.$data.init) {
      baseDataPanel.$data.init = true;
      reloadBaseDataTree();
    }
  });

  $('#nav-workflow').click(function () {
    $(this).addClass('navigator-bar-focus');
    $(this).siblings().removeClass('navigator-bar-focus');
    // $('#J-workspace-filter').hide();
    $('#box > .module').removeClass('active');
    $('#workflow').addClass('active');

    if (!propertyPanel.$data.init) {
      propertyPanel.$data.init = true;
      init();
    }
  });

  $("#nav-business").click(function (e) {
    if (bizPackPanel == null) {
      bizPackPanel = new Vue({
        el: '#business-pack',
        data: {
          init: false,
          baseData: [],
          showTemplates: false,
          imgs: [
            {
              createTime: null,
              dateIndex: '',
              formId: '',
              oid: '0',
              packId: '',
              tableId: '',
              tmplImage: '',
              tmplDesc: 'this is for something big...',
              tmplName: 'Template 1',
              updateTime: '',
              userId: ''
            },
            {
              createTime: null,
              dateIndex: '',
              formId: '',
              oid: '14',
              packId: '',
              tableId: '',
              tmplImage: '',
              tmplDesc: 'just the description for template.....',
              tmplName: 'Template 62',
              updateTime: '',
              userId: ''
            }
          ]
        },
        methods: {
          choseTemplate: function (tid) {
            alert(tid);
            this.showTemplates = false;
          },
          closeTemplate: function () {
            this.showTemplates = false;
          },
          setBaseDataCell: function (groupName) {
            cn.getCurCellPlus().selection().tag("cus:bsd:" + groupName.groupName + ":" + groupName.dataShowType);
            //alert(cn.getCurCellPlus().selection().tag());
            // var data = [
            //   { "id" : "uid1", "parent" : "#", "text" : "abc" },
            //   { "id" : "uid2", "parent" : "#", "text" : "xyz" },
            //   { "id" : "uid3", "parent" : "uid1", "text" : "oo" },
            //   { "id" : "uid4", "parent" : "uid1", "text" : "ee" },
            //   { "id" : "uid5", "parent" : "uid2", "text" : "jj" },
            //   { "id" : "uid6", "parent" : "uid2", "text" : "pp" },
            // ];
            // cn.getCurCellPlus().selection().cellType(new JsTreeCellType(data));
            //cn.getCurCellPlus().selection().offsetBlock(1,0).cellType(new DatePickerCellType()).width(100).formatter("yyyy年MM月dd日");
          },
          clearBaseData: function () {
            cn.getCurCellPlus().selection().foreachCell(function (cpl, rg) {
              if (cn.isCellCusType(rg, "basedata")) {
                rg.tag("");
                rg.cellType(cpUtil.getNewTextCell());
              }
            });
          },
          setBaseData: function () {
            cn.getCurCellPlus().selection().foreachCell(function (cpl, rg) {
              if (cn.isCellCusType(rg, "basedata")) {
                rg.tag("");
                rg.cellType(cpUtil.getNewTextCell());
              }
            });
          },
          setAutoCode: function () {
            var autocode = cn.cellTypeEx(cn.getCurCellPlus().selection());
            if (autocode != null && autocode == 'autocode') {
              autocode = cn.getCurCellPlus().selection().tag();
              autocode = cm.strSplitIdx(autocode, ":", 1);
            }
            else {
              autocode = null;
            }
            autocodeModal.showModal(autocode, function (data) {
              var ret = yddser.addOrUpdateCode(data);
              if (cm.dataNotOk(ret)) {
                cn.showFailedDlg(ret.msg);
              }
              else {
                var cell = cn.getCurCellPlus();
                cell.selection().tag("cus:" + data.oid);
              }
            });
          },
          clearAutoCode: function () {
            cn.getCurCellPlus().selection().foreachCell(function (cpl, rg) {
              if (cn.isCellCusType(rg, "autocode")) {
                rg.tag("");
              }
            });
          }
        }
      });

      reloadBizPackForm();
    }
    $(this).addClass('navigator-bar-focus');
    $(this).siblings().removeClass('navigator-bar-focus');
    // $('#J-workspace-filter').show();
    $('#box > .module').removeClass('active');
    $('#business-pack').addClass('active');

    // if (!$(e.target).hasClass("ydd-loaded")) {
    //   $('.packheader').on('click', function (e) {
    //     var $confirm = $('#doc-modal-1');
    //     var $confirmBtn = $confirm.find('[data-am-modal-confirm]');
    //     var $cancelBtn = $confirm.find('[data-am-modal-cancel]');
    //     $confirmBtn.off('click.confirm.modal.amui').on('click', function () {
    //       console.log('cf');
    //     });

    //     $cancelBtn.off('click.cancel.modal.amui').on('click', function () {
    //       console.log('cn');
    //     });

    //   });

      
    //   $(e.target).addClass("ydd-loaded");
    // }


  });
  $("#nav-business").click();

  $('#nav-userinfo').click(function () {
    // $('#box > .module').removeClass('active');
    //$('#user-info').addClass('active');
  });

  var windowWidth = $(window).width();
  $("#business-pack .ew-resize").bind("mousedown", function (e) {
    var disX = (e || event).clientX;
    document.onmousemove = function (e) {
      if (e.clientX > 260 && e.clientX < 462) {
        // console.log(e.clientX);s
        $('#top').width(e.clientX - 60);
        $('#rightBox').width(windowWidth - e.clientX - 1);
        var cell = cn.getCurCellPlus();
        if (cell) {
          var status = cell.tabStripVisible();
          cell.tabStripVisible(!status);
          cell.tabStripVisible(status);
        }
      }
    };
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmouseup = null;
    };
    return false
  });

  $("#user-panel .ew-resize").bind("mousedown", function (e) {
    var disX = (e || event).clientX;
    var self = this;
    document.onmousemove = function (e) {
      if (e.clientX > 260 && e.clientX < 462) {
        $(self).parents('.left-side').width(e.clientX - 60).next().width(windowWidth - e.clientX - 1).css('left', e.clientX - 60);
      }
    };
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmouseup = null;
    };
    return false
  });

  var $chromeTabsExampleShell = $('.chrome-tabs-shell')
  chromeTabs.init({
    $shell: $chromeTabsExampleShell,
    minWidth: 45,
    maxWidth: 160,
    fnTabClick: cn.tabClick,
    fnTabClose: cn.tabClose
  });
  $chromeTabsExampleShell.bind('chromeTabRender', function () {
    var $currentTab = $chromeTabsExampleShell.find('.chrome-tab-current');
    if ($currentTab.length && window['console'] && console.log) {
      //console.log('Current tab index', $currentTab.index(), 'title', $.trim($currentTab.text()), 'data', $currentTab.data('tabData').data);
    }
    if ($currentTab.length == 0) {
      $('#workspace_toolbar_panel').hide();
      $('#chrome-tabs-panel').hide();
      $('#rightBox').css('background', 'url(../main/newLogin_files/resources/images/bg.jpg) no-repeat');
    }
  });


  $('#J-toggle-sidebar').click(function () {
    // var arrow =
    if ($(this).find('span').hasClass('sicon-left-arrow')) {
      $(this).find('span').removeClass('sicon-left-arrow');
      $(this).find('span').addClass('sicon-right-arrow');
      $('#top').addClass('hide');
      $('#rightBox').css('width', $('#rightBox').width() + $('#top').width());

      var cell = cn.getCurCellPlus();
      var status = cell.tabStripVisible();
      cell.tabStripVisible(!status);
      cell.tabStripVisible(status);

    } else {
      $(this).find('span').removeClass('sicon-right-arrow');
      $(this).find('span').addClass('sicon-left-arrow');
      $('#top').removeClass('hide');
      $('#rightBox').css('width', $('#rightBox').width() - $('#top').width());

      var cell = cn.getCurCellPlus();
      var status = cell.tabStripVisible();
      cell.tabStripVisible(!status);
      cell.tabStripVisible(status);
    }
  });

  $('#business-pack .J-dimension-search').click(function () {
    if ($(this).parent().prev().hasClass('hideimportant')) {
      $(this).parent().prev().removeClass('hideimportant');
      $(this).parent().prev().find('input').focus();
      $(this).parent().prev().prev().addClass('hide');
    } else {
      $(this).parent().prev().addClass('hideimportant');
      $(this).parent().prev().prev().removeClass('hide');

      $('.J-filter-dimension').val('');
      $('.cube_dimension_tree.dimension_tree').jstree(true).clear_search();
    }
  });

  $('#business-pack .J-search-clear').click(function () {
    $(this).prev().val('');
    $('.cube_dimension_tree.dimension_tree').jstree(true).clear_search();
  });

  var to = false;
  $('#business-pack .J-filter-dimension').keyup(function () {
    if (to) {
      clearTimeout(to);
    }
    to = setTimeout(function () {
      var v = $('.J-filter-dimension').val();
      $('.cube_dimension_tree.dimension_tree').jstree(true).search(v);
    }, 250);
  });

  $('.cube_dimension_tree.dimension_tree').on('select_node.jstree', function (node, ele) {
    var uid = ele.node.id;
    if (cm.strStartWith(uid, 'pk')) {
      return;
    }
    $('#workspace_toolbar_panel').show();
    $('#chrome-tabs-panel').show();
    $('#rightBox').css('background', 'none');
    var rs = cn.getTabId(uid);
    if (rs) {
      rs.click();
    } else {
      // var tabName = $('#' + ele.node.id + ' > a').text();
      // var tabData = cn.genTabData("", tabName, {type: 'local', id: uid});
      // cn.addTab(tabData);
      var cpl = cn.openForm(null, ele);
      cn.setCplFormTableArrPos(cpl, function (cpsheet) {
        cpsheet.readonly(false);
      }, function (cprg) {
        cprg.readonly(false);
      });
    }
  }).on('hover_node.jstree', function (node, ele) {
    var setOptions = function() {
      btPop.$data.nodeId = ele.node.id;
      btPop.$data.curNode = ele.node;
      btPop.$data.showBtns = true;
      btPop.$data.jstree = '';
    }
    addSettings('.cube_dimension_tree.dimension_tree', ele, setOptions);
  }).jstree({
    "core": {
      "animation": 0,
      "check_callback": true,
      'force_text': true,
      // "themes" : { "stripes" : true },
      'data': {}
    },
    "search": {
      "show_only_matches": true
    },
    "types": {
      "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
      "root": {"icon": "./img/folder.png", "valid_children": ["default"]},
      "default": {"valid_children": ["default", "file"]},
      "file": {"icon": "./img/file.png", "valid_children": []}
    },
    "plugins": ["search", "types", "wholerow"]
  });

  var gvc = null, gvc2 = null;
  $('.ydd-icon-btn').on('click', function (e) {
    var attrVal = $(e.target).attr("operatetype");
    if (attrVal == 'newpack' || attrVal == 'newform' || attrVal == 'newlocal') {
      var title = "", styleData = "";
      if (attrVal == 'newlocal') {
        var dd = cm.dtToLYMDMS();
        var tabData = cn.genTabData("", "local", {type: 'local', id: "local" + cm.dtToLong()});
        cn.addTab(tabData);
      }
    }
    else if (attrVal == 'clearinput') {
      $(e.target).parent().find('.ydd-searh-input').val('');
    }
  });

  $('.ydd-pack').on('click', function (e) {

    if ($(e.target).hasClass('data-am-modal-confirm')) {
      var pack = {};
      pack.name = $('#InputPackName').val();
      if (pack != null) {
        var ret = yddser.addOrUpdatePack(pack).data;
        cn.yddToJstree(ret);
        var ref = $('.cube_dimension_tree').jstree(true);
        var ddd = ref.create_node("#", ret, 'first');
      }
    }
  });

  $('.ydd-form').on('click', function (e) {

    if ($(e.target).hasClass('data-am-modal-confirm')) {
      var data = gvc.getSheet(0).getPrefixVarObjJs('Ref$');
      var CurrentNode = $('.cube_dimension_tree').jstree(true).get_selected(true);
      var form = yddser.addOrUpdateForm({
        name: formName,
        type: data.formType,
        packId: CurrentNode[0].original.oid
      }).data;
      cn.yddToJstree(form);
      var ref = $('.cube_dimension_tree').jstree(true);
      var ret = ref.create_node(CurrentNode[0], form, 'first');
      var tabData = cn.genTabData("", ret.text, ret);
      cn.addTab(tabData);
    }
  });

  $('.tabbar-item').on('mouseover', function (e) {

    var vv = $('.tabbar-item.active');
    targetCon = vv.attr('data-target');
    $('.' + targetCon).addClass('hideimportant');
    vv.removeClass('active');

    $(e.target).addClass('active');
    var targetCon = $(e.target).attr('data-target');
    $('.' + targetCon).removeClass('hideimportant');

  }).on('mouseout', function (e) {

  });

  $('.ydd-dropdown').on('mouseover', function (e) {

    if (!$(e.currentTarget).hasClass('am-active')) {
      var vv = $(e.currentTarget).find('.am-dropdown-toggle');
      vv.click();
    }
  }).on('mouseleave', function (e) {

    if ($(e.currentTarget).hasClass('am-active')) {
      var vv = $(e.currentTarget).find('.am-dropdown-toggle');
      vv.click();
    }
  });

  $("#J-bg-color").spectrum({
    allowEmpty: true,
    color: "#ECC",
    showInput: true,
    containerClassName: "full-spectrum",
    showInitial: true,
    showPalette: true,
    showSelectionPalette: true,
    showAlpha: true,
    maxPaletteSize: 10,
    preferredFormat: "hex",
    localStorageKey: "spectrum.demo",
    move: function (color) {

    },
    show: function () {

    },
    beforeShow: function () {

    },
    hide: function (color) {

    },
    change: function (color) {
      cellDgnEvent.colorPickChange(2, color);
    },

    palette: [
      ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", /*"rgb(153, 153, 153)","rgb(183, 183, 183)",*/
        "rgb(204, 204, 204)", "rgb(217, 217, 217)", /*"rgb(239, 239, 239)", "rgb(243, 243, 243)",*/ "rgb(255, 255, 255)"],
      ["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
        "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
      ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
        "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
        "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
        "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
        "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
        "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
        "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
        "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
        /*"rgb(133, 32, 12)", "rgb(153, 0, 0)", "rgb(180, 95, 6)", "rgb(191, 144, 0)", "rgb(56, 118, 29)",
         "rgb(19, 79, 92)", "rgb(17, 85, 204)", "rgb(11, 83, 148)", "rgb(53, 28, 117)", "rgb(116, 27, 71)",*/
        "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
        "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
    ]
  });
  $("#J-font-color").spectrum({
    allowEmpty: true,
    color: "#ECC",
    showInput: true,
    containerClassName: "full-spectrum",
    showInitial: true,
    showPalette: true,
    showSelectionPalette: true,
    showAlpha: true,
    maxPaletteSize: 10,
    preferredFormat: "hex",
    localStorageKey: "spectrum.demo",
    move: function (color) {

    },
    show: function () {

    },
    beforeShow: function () {

    },
    hide: function (color) {

    },
    change: function (color) {
      cellDgnEvent.colorPickChange(1, color);
    },

    palette: [
      ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", /*"rgb(153, 153, 153)","rgb(183, 183, 183)",*/
        "rgb(204, 204, 204)", "rgb(217, 217, 217)", /*"rgb(239, 239, 239)", "rgb(243, 243, 243)",*/ "rgb(255, 255, 255)"],
      ["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
        "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
      ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
        "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
        "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
        "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
        "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
        "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
        "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
        "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
        /*"rgb(133, 32, 12)", "rgb(153, 0, 0)", "rgb(180, 95, 6)", "rgb(191, 144, 0)", "rgb(56, 118, 29)",
         "rgb(19, 79, 92)", "rgb(17, 85, 204)", "rgb(11, 83, 148)", "rgb(53, 28, 117)", "rgb(116, 27, 71)",*/
        "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
        "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
    ]
  });

  $('#newDept-getDept-Btn').click(function () {
    showDeptUserModal("", function (data, selDepts, selUsers) {
      var bfnd = false;
      for (var i = 0; i < selDepts.length; i++) {
        if (selDepts[i].name != null) {
          bfnd = true;
          $('#newDept-getDept').val(selDepts[i].name);
          $('#newDept-getDept').attr("deptCode", selDepts[i].deptCode);
          $('#newDept-getDept').attr("deptId", selDepts[i].id);
        }
      }
      if (!bfnd) {
        $('#newDept-getDept').attr("deptCode", "");
        $('#newDept-getDept').attr("deptId", "");
        $('#newDept-getDept').val("");
      }
    }, "department");

  });

  $('.group-item').on('click', function (e) {
    if ($(e.currentTarget).hasClass('group-font-style')) {
      var $a = $(e.target).parent();
      var $li = $a.parent();
      if ($a.attr('id') == 'J-font-bold') {
        cellDgnEvent.setClFontBold();
      }
      else if ($a.attr('id') == 'J-font-italic') {
        var cell = cellDgnEvent.getCurCell();
        var strO = cell.selection().font();
        var style = cm.getFontStyle(strO);
        if (style == null || style != "italic") {
          cell.selection().font(null, null, null, 'italic');
        }
        else {
          cell.selection().font(null, null, null, 'normal');
        }
      }
      else if ($a.attr('id') == 'J-font-underline') {
        var cell = cellDgnEvent.getCurCell();
        var style = cell.selection().textDecoration();
        if (style != null && ((style & GcSpread.Sheets.TextDecorationType.Underline) == GcSpread.Sheets.TextDecorationType.Underline)) {
          style = style & ~GcSpread.Sheets.TextDecorationType.Underline;
          cell.selection().textDecoration(style);
        }
        else {
          if (style == null)
            style = 0;
          cell.selection().textDecoration((GcSpread.Sheets.TextDecorationType.Underline | style));
        }

      }
      else if ($a.attr('id') == 'J-font-through') {
        var cell = cellDgnEvent.getCurCell();
        var style = cell.selection().textDecoration();
        if (style != null && ((style & GcSpread.Sheets.TextDecorationType.LineThrough) == GcSpread.Sheets.TextDecorationType.LineThrough)) {
          style = style & ~GcSpread.Sheets.TextDecorationType.LineThrough;
          cell.selection().textDecoration(style);
        }
        else {
          if (style == null)
            style = 0;
          cell.selection().textDecoration((GcSpread.Sheets.TextDecorationType.LineThrough | style));
        }

      }
      cellDgnEvent.updateFontStyle();
    }
    else if ($(e.currentTarget).hasClass('group-cutcopy')) {
      if ($(e.currentTarget).hasClass('J-cut')) {
        console.log(e.target);
      }
    }
    else if ($(e.currentTarget).hasClass('group-table-insert')) {
      var a = $(e.target).parent();
      var cell = cn.getCurCellPlus();
      if (a.hasClass('J-insert-row')) {
        cell.selection().insertRow(1);
      }
      else if (a.hasClass('J-insert-col')) {
        cell.selection().insertCol(1);
      }
      else if (a.hasClass('J-delete-row')) {
        cell.selection().deleteRow();
      }
      else if (a.hasClass('J-delete-col')) {
        cell.selection().deleteCol();
      }
    }
    else if ($(e.currentTarget).hasClass('group-setting-view')) {
      var a = $(e.target).parent();
      var cell = cn.getCurCellPlus();
      if (a.hasClass('J-setting-tab')) {
        var v = cell.tabStripVisible();
        cell.tabStripVisible(!v);
      }
      else if (a.hasClass('J-setting-rowheaderV')) {
        var v = cell.currentSheet2().rowHeaderVisible();
        cell.currentSheet2().rowHeaderVisible(!v);
      }
      else if (a.hasClass('J-setting-colheaderV')) {
        var v = cell.currentSheet2().colHeaderVisible();
        cell.currentSheet2().colHeaderVisible(!v);
      } else if (a.hasClass('J-setting-new')) {
        var v = cell.newTabVisible();
        cell.newTabVisible(!v);
      } else if (a.hasClass('J-setting-dragfill')) {
        var v = cell.canUserDragFill();
        cell.canUserDragFill(!v);
        v = cell.canUserDragDrop();
        cell.canUserDragDrop(!v);
      }
      cellDgnEvent.updateSetting();
    }
    else if ($(e.currentTarget).hasClass('group-link')) {
      var a = $(e.target).parent();
      var cell = cn.getCurCellPlus();
      if (a.hasClass('J-multi-line')) {
        cellDgnEvent.setClWordWrap();
        cellDgnEvent.updateFontStyle();
      }
    }
    else if ($(e.currentTarget).hasClass('group-table-combine')) {
      var a = $(e.target).parent();
      var cell = cn.getCurCellPlus();
      if (a.hasClass('J-combined-cell')) {
        cell.selection().merge();
      }
      else if (a.hasClass('J-split-cell')) {
        cell.selection().unMerge();
      }
      else if (a.hasClass('J-hide-row')) {

      }
      else if (a.hasClass('J-hide-col')) {

      }
      else if (a.hasClass('J-fixed-colrow')) {
        cell.currentSheet2().setFixedCol(cell.selection().c1());
        cell.currentSheet2().setFixedRow(cell.selection().r1());
      }
    }
    else if ($(e.currentTarget).hasClass('group-functions-view')) {
      var a = $(e.target).parent();
      if (a.hasClass('J-fx')) {
        var curTab = cn.getCurTabForm();
        if (curTab != null) {
          var fxDialogId = 'fx-dialog-' + curTab.id;
          if ($('#' + fxDialogId).length > 0) {
            $('#' + fxDialogId).dialog('open');
          } else {
            var dialog = $($('#fx-dialog').html()).attr('id', fxDialogId);
            $(dialog).dialog({
              appendTo: '#gcDiv-' + curTab.id,
              modal: true,
              minWidth: 400,
              minHeight: 350,
              width: 400,
              height: 350,
              classes: {
                'ui-dialog-titlebar-close': 'am-icon-close'
              },
              buttons: [{
                text: '取消',
                click: function () {
                  $(this).dialog('close');
                }
              },
                {
                  text: "确定",
                  click: function () {
                    alert('当前选定公式为：' + $(this).find('input').val());
                  }
                }
              ],
              create: function () {
                var self = this;
                var classes = [{
                  name: 'all',
                  label: '全部'
                }, {
                  name: 'stat',
                  label: '统计'
                }, {
                  name: 'lookup',
                  label: '查找与引用'
                }, {
                  name: 'date',
                  label: '日期与时间'
                }, {
                  name: 'finance',
                  label: '财务'
                }, {
                  name: 'logic',
                  label: '逻辑'
                }, {
                  name: 'math',
                  label: '数学与三角函数'
                }, {
                  name: 'text',
                  label: '文本'
                }, {
                  name: 'user',
                  label: '用户'
                }];
                var functions = [
                  {
                    name: 'ABS',
                    class: 'math',
                    descrition: '返回给定数值的绝对值,即不带符号的数值.',
                    pattern: 'ABS(Value)'
                  }, {
                    name: 'MAX',
                    class: 'stat',
                    description: '返回一组数值中的最大值,忽略逻辑值及文本.',
                    pattern: 'MAX(value1, value2, ...)'
                  }, {
                    name: 'CHOOSE',
                    class: 'lookup',
                    description: '根据给定的索引值，从参数串中选出相应值或操作.这些value可以是单元格范围.',
                    pattern: 'CHOOSE(index, value1, value2, ...)'
                  }, {
                    name: 'HOUR',
                    class: 'date',
                    description: '返回小时数值.',
                    pattern: 'HOUR(value)'
                  }, {
                    name: 'SLN',
                    class: 'finance',
                    description: '返回固定资产的每期线性折旧费.',
                    pattern: 'SLN(cost, salvage, lifetime)'
                  }, {
                    name: 'AND',
                    class: 'logic',
                    description: '如果所有参数值均为TRUE,则返回TRUE.',
                    pattern: 'AND(value1, value2, ...)'
                  }, {
                    name: 'EXACT',
                    class: 'text',
                    description: '比较两个字符串是否完全相同(区分大小写),返回TRUE或FALSE',
                    pattern: 'EXACT(v1, v2)'
                  }, {
                    name: 'IF',
                    class: 'logic',
                    description: '判断是否满足某个条件,如果满足返回true-value,不满足返回false-value.',
                    pattern: 'IF(logical-expression, true-value, [false-value])'
                  }
                ];
                var classSelect = $(self).find('select:first');
                var functionSelect = $(self).find('select:last');
                for (var i = 0; i < classes.length; i++) {
                  var option = $('<option></option>');
                  option.attr('value', classes[i].name);
                  option.text(classes[i].label);
                  classSelect.append(option);
                }
                classSelect.change(function () {
                  functionSelect.empty();
                  var hasSelected = false;
                  for (var i = 0; i < functions.length; i++) {
                    if (this.value == 'all' || this.value == functions[i].class) {
                      var option = $('<option></option>');
                      option.attr('value', functions[i].name);
                      option.text(functions[i].name);
                      option.dblclick(function () {
                        $(self).find('input').insertContent(this.value);
                      });
                      functionSelect.append(option);
                      if (!hasSelected) {
                        hasSelected = true;
                        option.attr('checked', 'checked');
                        functionSelect.val(functions[i].name);
                        $(self).find('div[data-target="description"]').text(functions[i].description);
                        $(self).find('div[data-target="pattern"]').text(functions[i].pattern);
                      }
                    }
                  }
                });

                functionSelect.change(function () {
                  for (var i = 0; i < functions.length; i++) {
                    if (this.value == functions[i].name) {
                      $(self).find('div[data-target="description"]').text(functions[i].description);
                      $(self).find('div[data-target="pattern"]').text(functions[i].pattern);
                    }
                  }
                });
              },
              drag: function (event, ui) {
                if (ui.position.left < 0) {
                  ui.position.left = 0;
                }
                if (ui.position.top < 40) {
                  ui.position.top = 40;
                }
              },
              resize: function (event, ui) {
                if (ui.position.top < 40) {
                  ui.position.top = 40;
                }
              }
            });
          }
        }
      } else if (a.hasClass('J-add-dataset')) {
        var formData = cn.getCurTabForm();
        if (formData == null) {
          cn.showFailedDlg('未发现表单, 请创建表单');
          return;
        }

        var datasetState = formData.cellPlus.formObj.datasetState;
        if (datasetState != null && datasetState == 1) {
          cn.showFailedDlg('当前已有数据项,不能再创建, 请查看');
          return;
        }

        var pid = formData.packId;
        var ret = yddser.getNewId('tb');
        if (ret == null || cm.dataNotOk(ret)) {
          cn.showFailedDlg(ret.msg);
          return;
        }

        var cp = formData.cellPlus;
        cn.initCpl(cp);
        var arr = cn.cprgToSqlFieldArr(cp.selection());
        var tableD = {};
        tableD.tableName = ret.data;
        tableD.oid = ret.data;
        tableD.tableType = 1; //主表数据项
        tableD.tableKey = 0;
        tableD.columns = arr;
        tableD.sheetName = cp.currentSheet2().customVar();
        addDataSet.$data.tabs = [];
        addDataSet.$data.tabs.push(tableD);
        $('#add-data-set').modal();
      }
      else if (a.hasClass('J-view-dataset')) {
        var formData = cn.getCurTabForm();
        if (formData == null) {
          $('#my-alert .am-modal-bd').text('未发现表单, 请创建表单');
          $('#my-alert').modal();
          return;
        }

        var tableArr = formData.cellPlus.formObj.tableArr;
        if (tableArr == null) {
          $('#my-alert .am-modal-bd').text('未发现数据项, 请添加数据项');
          $('#my-alert').modal();
          return;
        }
        var initTabs = [];
        for (var i = 0; i < tableArr.length; i++) {
          var tab = $.extend({keywords: ''}, tableArr[i]);
          for (var j = 0; j < tab.columns.length; j++) {
            tab.columns[j].show = true;
          }
          initTabs.push(tab);
        }
        viewDateSet.$data.tabs = initTabs;
        $('#view-data-set').modal();
        $('#view-data-set .am-modal-dialog').draggable();
      }
      else if (a.hasClass('J-create-dataset')) {
        var formData = cn.getCurTabForm();
        var tableArr = formData.cellPlus.formObj.tableArr;
        if (tableArr == null) {
          $('#my-alert .am-modal-bd').text('未发现数据项, 请添加数据项');
          $('#my-alert').modal();
          return;
        }
        var datasetState = formData.cellPlus.formObj.datasetState;
        if (datasetState != null && datasetState == 1) {
          $('#my-alert .am-modal-bd').text('当前已有数据项,不能再创建, 请查看');
          $('#my-alert').modal();
          return;
        }

        cm.myAlertFunc("确定创建数据项吗?创建后将不能修改",formData,function (inData) {
            cn.cprgToFieldVar2(inData.cellPlus);
            var retD = yddser.createTable(inData.cellPlus, tableArr);
            if (retD != null && cm.dataOk(retD)) {
              inData.cellPlus.formObj.datasetState = 1;
            } else {
              cm.myAlert(cn.getRetMsg(retD));
              return;
            }
          });
      }
      else if (a.hasClass('J-delete-sub')) {
        var formData = cn.getCurTabForm();
        var tableArr = formData.cellPlus.formObj.tableArr;
        var cp = formData.cellPlus;
        var sel = cp.selection();

        for (var i = 0; i < tableArr.length; i++) {
          if (tableArr[i].tableType == 2) {
            var htRg = "RD:HTRG:" + tableArr[i].oid;
            htRg = cp.getRangeByCustomVar(htRg);
            if (htRg.isRgInThis(sel)) {
              htRg.htRgDeleteItem(sel, null, function (retCom) {
                var curRg = retCom.curHTRgOne;
                var offsetArr = retCom.offsetArr;
                var headRg = retCom.headRg;
                var newOne = curRg.cloneNew();
                var did = newOne.genOffsetRg(offsetArr[0]).tag();
                var vv = did;
                if (formData.cellPlus.tmpData == null) {
                  formData.cellPlus.tmpData = {};
                  formData.cellPlus.tmpData.deletedDids = {};
                }
                if (formData.cellPlus.tmpData.deletedDids[tableArr[i].oid] == null) {
                  formData.cellPlus.tmpData.deletedDids[tableArr[i].oid] = [];
                }
                formData.cellPlus.tmpData.deletedDids[tableArr[i].oid].push(did);
              });
              return;
            }
          }
        }

        $('#my-alert .am-modal-bd').text('未发现子表数据区域');
        $('#my-alert').modal();
        return;
      }
      else if (a.hasClass('J-insert-sub')) {
        var formData = cn.getCurTabForm();
        var tableArr = formData.cellPlus.formObj.tableArr;
        var cp = formData.cellPlus;
        var sel = cp.selection();

        for (var i = 0; i < tableArr.length; i++) {
          if (tableArr[i].tableType == 2) {
            var htRg = "RD:HTRG:" + tableArr[i].oid;
            htRg = cp.getRangeByCustomVar(htRg);
            if (htRg.isRgInThis(sel)) {
              var back = cp.defaultDragFillType();
              cp.defaultDragFillType(3);
              htRg.htRgAppendItem(sel, 1, null, function (retCom, num, dir) {
                var curRg = retCom.curHTRgOne;
                var offsetArr = retCom.offsetArr;
                var headRg = retCom.headRg;
                var newOne = curRg.cloneNew();

                for (var i = 1; i <= num; i++) {
                  if (dir == 4) {
                    newOne.offsetBlock(1, 0);
                    var did = yddser.getNewId('did');
                    newOne.genOffsetRg(retCom.offsetArr[0]).tag(did.data);
                  }
                  else if (dir == 2) {
                    newOne.offsetBlock(-1, 0);
                    var did = yddser.getNewId('did');
                    newOne.genOffsetRg(retCom.offsetArr[0]).tag(did.data);
                  }
                }
              });
              cp.defaultDragFillType(back);
              return;
            }
          }
        }

        $('#my-alert .am-modal-bd').text('未发现子表数据区域');
        $('#my-alert').modal();
        return;
      }
      else if (a.hasClass('J-delete-dataset')){
        var formData = cn.getCurTabForm();
        cm.myAlertFunc("确定要删除数据项和数据吗?", formData.oid, function (formId) {
          var ret = yddser.deleteDataset(formId);
          if (cm.dataOk(ret)){
            cn.setCplFormTableArrPosNone(formData.cellPlus);
          }
        });
      }
    }
    else if ($(e.currentTarget).hasClass('group-template-view')) {
      var a = $(e.target).parent();
      if (a.hasClass('new-template')) {

        var tabobj = cn.getCurTabForm();
        var formData = yddser.getForm(tabobj.id);//form和tableArr data
        if (cm.dataNotOk(formData)) {
          cm.myAlert("打开表单失败!");
          return;
        }
        var ret = yddser.getNewId("fmtm");
        if (cm.dataNotOk(ret)) {
          cn.showFailedDlg(ret.msg);
          return;
        }

        var obj = {};
        obj.packId = tabobj.packId;
        obj.formId = tabobj.id;
        obj.oid = ret.data;
        obj.tableId = "";
        obj.userId = "";
        obj.dataIndex = "";
        obj.tmplName = "TM-" + tabobj.name;
        obj.tmplDesc = "";
        obj.tmplImage = "";
        var retD = yddser.addOrUpdateFormTmpl(obj);
        if (cm.dataNotOk(retD)) {
          cm.myAlert("创建表单模板失败:" + retD.msg);
          return;
        }

        formData = formData.data;
        var tabD = cn.genTabData("", obj.tmplName, {type: 'local', id: obj.oid});
        var cp = cn.addTab(tabD);
        cp.loadFromJsonStr(formData.styleData);
        cp.formObj = formData;
        cp.formTmpl = obj;
        cn.setCplFormTableArrPos(cp, function (cpsheet) {
          cpsheet.readonly(true);
        }, function (cprg) {
          cprg.readonly(false);
        });
      } else if (a.hasClass('save-template')) {
        var canvas = $('#gcDiv-' + cn.getCurTabForm().id + 'vp_vp')[0];
        var image = canvas.toDataURL("image/png");

        var tabData = cn.getCurTabForm();
        var retD = yddser.addOrUpdateFormTmplData(tabData.cellPlus, "");
        if (cm.dataNotOk(retD)) {
          cm.myAlert(retD.msg);
          return;
        }

        var formTmpl = tabData.cellPlus.formTmpl;
        formTmpl.tmplImage = cm.encode(image);
        formTmpl.dataIndex = retD.data;
        var tabData = cn.getCurTabForm();
        var retD = yddser.addOrUpdateFormTmpl(formTmpl);
        if (cm.dataOk(retD)) {
          cm.myAlert("保存成功");
        }
        else {
          cm.myAlert(retD.msg);
        }

      } else if (a.hasClass('sub-template')) {
        alert('子模板')
      }
      else if (a.hasClass('open-template')) {
        bizPackPanel.$data.showTemplates = true;
        // var txt = cm.inputDlg(function (fmtmId) {
        //   var retD = yddser.getFormTmpl(fmtmId);
        //   if (cm.dataNotOk(retD)) {
        //     cm.myAlert(retD.msg);
        //   }

        //   var tabD = cn.genTabData("", retD.data.tmplName, {type: 'local', id: retD.data.oid});
        //   var cp = cn.addTab(tabD);
        //   cp.loadFromJsonStr(retD.data.formObj.styleData);
        //   cp.formObj = retD.data.formObj;
        //   delete retD.data.formObj;
        //   cp.formTmpl = retD.data;
        //   cn.setCplFormTableArrPos(cp, function (cpsheet) {
        //     cpsheet.readonly(true);
        //   }, function (cprg) {
        //     cprg.readonly(false);
        //   });

        //   var reqResData = retD.data.dataObj;
        //   delete retD.data.dataObj;
        //   cn.setCplFormData(cp, reqResData);
        // });
      }
    }
    else if ($(e.currentTarget).hasClass('group-item')) {
      var $a = $(e.target).parent();
      var $li = $a.parent();
      if ($a.hasClass('J-save')) {
        var tabData = cn.getCurTabForm();
        if (tabData != null) {
          var gcStyle = tabData.cellPlus.saveToJsonStr()
          yddser.saveFormStyle(tabData.oid, gcStyle);
        }
      }
      else if ($a.hasClass('J-open-local')) {
        var result = cn.showOpenFile(function (data) {
          var form = cn.getCurTabForm();
          form.cellPlus.loadFromJsonStr(data);
        });
      }
    }
  });

  $('.ydd-dropdown').on('click', function (e) {
    //var vv = $('.ydd-dropdown>.am-dropdown-toggle');
    //if (vv != null)
    //    vv.click();
    if ($(e.currentTarget).hasClass('am-active')) {
      var vv = $('#box');
      vv.click();
    }

    if ($(e.target).attr('data-type') == 'item') {

      var ns = GcSpread.Sheets;

      var span = '<span class="am-icon-caret-down"><span>';
      if ($(e.currentTarget).attr("data-type") == "font-family") {
        $('#J-font-family').html($(e.target).text() + span);
        cellDgnEvent.setClFontName($(e.target).text());
      } else if ($(e.currentTarget).attr("data-type") == "font-size") {
        $('#J-font-size').html($(e.target).text() + span);
        cellDgnEvent.setClFontSize($(e.target).text());
      } else if ($(e.currentTarget).attr("data-type") == "text-align") {
        var cell = cellDgnEvent.getCurCell();
        var tt = $(e.target).parent().attr("data-param");
        if (tt == null)
          tt = $(e.target).parent().parent().attr("data-param");
        if (tt == 'left') {
          cell.selection().hAlign(ns.HorizontalAlign.left);
        }
        else if (tt == 'right') {
          cell.selection().hAlign(ns.HorizontalAlign.right);
        }
        else if (tt == 'center') {
          cell.selection().hAlign(ns.HorizontalAlign.center);
        } else if (tt == 'top') {
          cell.selection().vAlign(ns.VerticalAlign.top);
        }
        else if (tt == 'bottom') {
          cell.selection().vAlign(ns.VerticalAlign.bottom);
        }
        else if (tt == 'vcenter') {
          cell.selection().vAlign(ns.VerticalAlign.center);
        }
      } else if ($(e.currentTarget).attr("data-type") == "cell-border") {
        var cell = cellDgnEvent.getCurCell();
        var tt = $(e.target).parent().attr("data-param");

        if (tt == null)
          tt = $(e.target).parent().parent().attr("data-param");
        if (tt == 'broder-all') {
          cell.selection().borderLeft(new ns.LineBorder("black", ns.LineStyle.thin));
          cell.selection().borderTop(new ns.LineBorder("black", ns.LineStyle.thin));
          cell.selection().borderRight(new ns.LineBorder("black", ns.LineStyle.thin));
          cell.selection().borderBottom(new ns.LineBorder("black", ns.LineStyle.thin));
        }
        else if (tt == 'broder-left') {
          cell.selection().borderLeft(new ns.LineBorder("black", ns.LineStyle.thin));
        }
        else if (tt == 'broder-top') {
          cell.selection().borderTop(new ns.LineBorder("black", ns.LineStyle.thin));
        }
        else if (tt == 'broder-right') {
          cell.selection().borderRight(new ns.LineBorder("black", ns.LineStyle.thin));
        }
        else if (tt == 'broder-bottom') {
          cell.selection().borderBottom(new ns.LineBorder("black", ns.LineStyle.thin));
        }
        else if (tt == 'broder-none') {
          cell.selection().borderLeft(new ns.LineBorder("black", ns.LineStyle.empty));
          cell.selection().borderTop(new ns.LineBorder("black", ns.LineStyle.empty));
          cell.selection().borderRight(new ns.LineBorder("black", ns.LineStyle.empty));
          cell.selection().borderBottom(new ns.LineBorder("black", ns.LineStyle.empty));
        }
      } else if ($(e.currentTarget).attr("data-type") == "cell-date-format") {
        var cell = cellDgnEvent.getCurCell();
        var tt = $(e.target).parent().attr("data-param");
        if (tt == null)
          tt = $(e.target).parent().parent().attr("data-param");
        if (tt == 'cell-date') {
          cell.selection().formatter(new ns.GeneralFormatter("yyyy/MM/dd", 0, "zh-cn"));
        }
        else if (tt == 'cell-time') {
          cell.selection().formatter("HH:mm:ss");
        }
        else if (tt = 'cell-fmt-none') {
          cell.selection().formatter("");
        }
      } else if ($(e.currentTarget).attr("data-type") == "cell-num-format") {
        var cell = cellDgnEvent.getCurCell();
        var tt = $(e.target).parent().attr("data-param");
        if (tt == null)
          tt = $(e.target).parent().parent().attr("data-param");
        if (tt == 'cell-percent') {
          cell.selection().formatter("0.00%");
        }
        else if (tt == 'cell-currency') {
          cell.selection().formatter("$0.00");
        }
        else if (tt == 'cell-num1') {
          cell.selection().formatter("#.##");
        } else if (tt == 'cell-num2') {
          cell.selection().formatter("0.0");
        } else if (tt == 'cell-num3') {
          cell.selection().formatter("0.00");
        }
        else if (tt = 'cell-fmt-none') {
          cell.selection().formatter("");
        }
      } else if ($(e.currentTarget).attr("data-type") == "cell-type") {
        var cell = cellDgnEvent.getCurCell();
        var tt = $(e.target).parent().attr("data-param");
        if (tt == null)
          tt = $(e.target).parent().parent().attr("data-param");
        if (tt == 'cell-button') {
          var type = cell.selection().cellType();
          if (!cpUtil.isButtonCell(type)) {
            type = cpUtil.getNewButtonCell();
          }
          buttonCell.$data.buttonText = type.text();
          buttonCell.$data.buttonBackColor = type.buttonBackColor();
          $('#buttonCellModal').modal({
            relatedTarget: this,
            onCancel: function (e) {
            },
            onConfirm: function (e) {
              type.text(buttonCell.$data.buttonText);
              type.buttonBackColor(buttonCell.$data.backColor);
              cell.selection().foreachJs(function (area, i) {
                area.cellType(cm.cloneObj(type));
              });
            }
          });
        }
        else if (tt == 'cell-checkbox') {
          var type = cell.selection().cellType();
          if (!cpUtil.isCheckBoxCell(type)) {
            type = cpUtil.getNewCheckBox();
          }

          checkboxCell.$data.checkboxText = type.caption();
          checkboxCell.$data.checkboxTrue = type.textTrue();
          checkboxCell.$data.checkboxFalse = type.textFalse();
          $('#checkboxCellModal').modal({
            relatedTarget: this,
            onCancel: function (e) {
            },
            onConfirm: function (e) {
              type.textTrue(checkboxCell.$data.checkboxTrue);
              type.textFalse(checkboxCell.$data.checkboxFalse);
              cell.selection().foreachJs(function (area, i) {
                area.cellType(cm.cloneObj(type));
              });
            }
          });
        } else if (tt == 'cell-combo') {
          var type = cell.selection().cellType();
          if (!cpUtil.isComboBoxCell(type)) {
            type = cpUtil.getNewComboBox();
          }

          comboCell.$data.items = type.items().toString();
          $('#comboCellModal').modal({
            relatedTarget: this,
            onCancel: function (e) {
            },
            onConfirm: function (e) {
              type.items(comboCell.$data.items.split(','));
              cell.selection().foreachJs(function (area, i) {
                area.cellType(cm.cloneObj(type));
              });
            }
          });
        }
        else if (tt = 'cell-fmt-none') {
          cell.selection().cellType(cpUtil.getNewTextCell());
        }
      }
    }
  });

  var $toggleButton = $('#doc-single-toggle');
  $toggleButton.on('click', function () {
    setButtonStatus();
  });

  function setButtonStatus() {
    var status = $toggleButton.hasClass('am-active') ? '未激活' : '激活';
    $('#doc-single-toggle-status').text(status);
  }

  $('#user-panel .user-nav li a').click(function () {
    $('#user-panel .module').removeClass('active');
    $($(this).attr('href')).addClass('active');
    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');
  });

  $('#base-data .user-nav li a').click(function () {
    $('#base-data .module').removeClass('active');
    $($(this).attr('href')).addClass('active');
    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');
  });

  $('#create-department').click(function () {
    var CurrentNode = $('#user-dept-tree').jstree(true).get_selected(true);
    if (CurrentNode.length > 0) {
      $('#newDept-getDept').attr("deptCode", CurrentNode[0].original.deptCode);
      $('#newDept-getDept').attr("deptId", CurrentNode[0].original.oid);
      $('#newDept-getDept').val(CurrentNode[0].original.deptName);
    }
    $('#deparment-prompt').modal({
      relatedTarget: this,
      onConfirm: function (e) {
        var deptCode = $('#newDept-getDept').attr("deptCode");
        if (deptCode == null || deptCode == "") {
          deptCode = 0;
        }
        var pdeptId = $('#newDept-getDept').attr("deptId");
        if (pdeptId == null || pdeptId == "") {
          pdeptId = "#";
        }
        var ret = yddser.getDeptSubCode(deptCode);
        if (cm.dataNotOk(ret)) {
          cn.showFailedDlg(ret.msg);
        }
        else {
          deptCode = ret.data;
          var dept = {};
          dept.oid = yddser.getNewId("dp").data;
          dept.deptName = e.data;
          dept.id = dept.oid;
          dept.name = dept.deptName;
          dept.deptCode = deptCode;
          ret = yddser.addOrUpdateDept(dept);
          if (cm.dataNotOk(ret)) {
            cn.showFailedDlg(ret.msg);
          }
          else {
            cn.yddToJstree(dept);
            $('#user-dept-tree').jstree('create_node', pdeptId, dept, 'last');
            $('#deparment-prompt').find('input').val('');
          }
        }
      },
      onCancel: function (e) {
        $('#deparment-prompt').find('input').val('');
      }
    })
  });

  $('#bulk-import').change(function () {
    var files = event.target.files;

    for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // if (!file.type.match('xlsx') && !file.type.match('xls')) {
      //     return;
      // }

      var picReader = new FileReader();

      picReader.addEventListener("load", function (event) {

        var textFile = event.target;

        console.log(textFile.result.length);

        var div = document.createElement("div");

        var wb = XLSX.read(textFile.result, {type: 'binary'});

        //console.log(wb);

        wb.SheetNames.forEach(function (sheetName) {
          var excelDate = [];
          var csv = XLSX.utils.sheet_to_csv(wb.Sheets[sheetName]);
          var lines = csv.split('\n');
          var titles = lines[0].split(',');
          for (var i = 1; i < lines.length; i++) {
            var ed = {};
            var cells = lines[i].split(',');
            for (var j = 0; j < cells.length; j++) {
              ed[titles[j]] = cells[j];
            }
            excelDate.push(ed);
          }
          console.log(excelDate);
        });

        alert('导入成功，请看控制台');
      });

      picReader.readAsBinaryString(file);
    }
  });

  $('#import-multi').click(function () {
    $('#deparment-prompt').modal({
      relatedTarget: this,
      onConfirm: function (e) {
        var node = {'id': new Date().getTime(), 'text': e.data, 'type': 'department'};
        var $obj = $('#user-dept-tree');
        $obj.jstree('create_node', 'company', node, 'last');
        $obj.jstree('open_node', 'company');
        var CurrentNode = $obj.jstree(true).get_selected(true);
        var ref = $obj.jstree(true);
        var ret = ref.create_node('#', node, 'first');

        $obj = $('#deparment-prompt');
        var deptname = $obj.find('input').val();
        $obj.find('input').val('');
      },
      onCancel: function (e) {
        $('#deparment-prompt').find('input').val('');
      }
    })
  });

  $('#newpack').click(function () {
    var $modal = $('#doc-modal-1');
    var title = "新增业务包";
    $modal.find('.am-modal-hd').html(title + '<a href="javascript: void(0)" class="am-close" data-am-modal-close>&times;</a>');
    $modal.find('.am-modal-bd').html('<input type="text" id="InputPackName" minlength="3" placeholder="业务包名称" class="am-form-field" required/>');
    $modal.modal('toggle');
  });

  $('#edit-pack-name').click(function () {
    $(this).parent().addClass('hide').next().removeClass('hide');
  });

  $('.dpt-search .J-dimension-search').click(function () {
    if ($('.dpt-search .text').hasClass('hide')) {
      $('.dpt-search .text').removeClass('hide');
      $('.dpt-search .text').next().addClass('hide');

      $('.dpt-search input').val('');
      $('#departments').jstree(true).clear_search();
    } else {
      $('.dpt-search .text').addClass('hide');
      $('.dpt-search .text').next().removeClass('hide');
    }
  });

  var dptTo;
  $('.dpt-search input').keyup(function () {
    var self = this;
    if (dptTo) {
      clearTimeout(dptTo);
    }
    dptTo = setTimeout(function () {
      var v = $(self).val();
      $('#departments').jstree(true).search(v);
    }, 250);
  })

  $('.dpt-search .J-search-clear').click(function () {
    $(this).prev().val('');
    $('#departments').jstree(true).clear_search();
  })


  var auth = null;
  var authed = false;

  function showDeptUserModal(inData, func, inState) {

    var retData = yddser.getDept("all", true);
    var retUser = yddser.getUser2("all", 1, 1);

    // 设置数据  auth.$data.users = [],   auth.$data.departments = []
    var auth = new Vue({
      el: '#authorize-users-confirm',
      data: {
        state: inState,
        deptId: '',
        users: retUser.data,
        departments: [],
        selDept: [],
        selUser: [],
      },
      methods: {
        deselectUser: function (user) {
          user.selected = false;
        },
        deselectDepartment: function (department) {
          department.selected = false;
          $('#department-select').jstree(true).deselect_node(department.id)
        },
        save: function () {
          this.selDept = [];
          this.selUser = [];
          var uCount = 0;
          for (var i = 0; i < this.users.length; i++) {
            if (this.users[i].selected) {
              this.selUser.push(this.users[i]);
            }
          }
          var dCount = 0;
          for (var i = 0; i < this.departments.length; i++) {
            if (this.departments[i].selected) {
              this.selDept.push(this.departments[i]);
            }
          }
          if (func != null) {
            func(inData, this.selDept, this.selUser);
          }
        },
        cancel: function () {
          this.selDept = [];
          this.selUser = [];
        }
      }
    });

    $('#authorize-users-confirm').modal();
    if (!authed) {
      authed = true;

      $('#departments').on('select_node.jstree', function (node, ele) {
        auth.$data.deptId = ele.node.original.oid;
      }).jstree({
        'core': {
          'multiple': false,
          'check_callback': true,
          'data': retData.data,
        },
        "types": {
          "#": {"max_children": 1, "max_depth": 4, "valid_children": ["company"]},
          "department": {"icon": "../main/img/department.png", "valid_children": ["default"]},
          "default": {"valid_children": ["default", "file"]},
          "company": {"icon": "../main/img/company.png", "valid_children": ["department"]}
        },
        "search": {
          "show_only_matches": true
        },
        "plugins": ["types", "wholerow", "search"]
      });


      $('#department-select').on('ready.jstree', function () {
        var data = $('#department-select').jstree(true)._model.data;
        for (key in data) {
          var node = data[key];
          auth.$data.departments.push({
            id: node.id, name: node.text, selected: false,
            deptCode: node.original != null ? node.original.deptCode : ""
          });
        }
      }).on('changed.jstree', function (node, selected) {
        for (var i = 0; i < auth.$data.departments.length; i++) {
          if (selected.selected.indexOf(auth.$data.departments[i].id) == -1) {
            auth.$data.departments[i].selected = false;
          } else {
            auth.$data.departments[i].selected = true;
          }
        }
      }).jstree({
        'core': {
          'multiple': true,
          'check_callback': true,
          'data': retData.data,
        },
        "types": {
          "#": {"max_children": 1, "max_depth": 4, "valid_children": ["company"]},
          "department": {"icon": "../main/img/department.png", "valid_children": ["default"]},
          "default": {"valid_children": ["default", "file"]},
          "company": {"icon": "../main/img/company.png", "valid_children": ["department"]},
        },
        'checkbox': {
          three_state: false
        },
        "plugins": ["types", "wholerow", "checkbox"]
      });
    }

  }

  $('#authorize-users').click(function () {
    showDeptUserModal(null, null, 'all');
  });


  var btPop = new Vue({
    el: '#business-tooltips',
    data: {
      showBtns: true,
      isAddReport: false,
      nodeId: '',
      userId:'',
      curNode: {},
      btName: '',
      placeHolder: '',
      jstree: '',
      disableReset: false
    },
    methods: {
      editUserReport: function () {
        $('#edit-auth').modal();
      },
      resetUserReport: function () {
        yddser.delRightToUserForm(this.userId, this.nodeId);
      },
      editName: function () {
        this.showBtns = false;
        this.isAddReport = false;
        if (this.isPackage) {
          this.placeHolder = '请输入业务包名称';
        } else {
          this.placeHolder = '请输入表单名称';
        }
        var inputele = this.$el.getElementsByTagName('input');
        setTimeout(function () {
          inputele[0].focus();
          console.log(inputele[0]);
        }, 0);
      },
      addForm: function () {
        this.showBtns = false;
        this.isAddReport = true;
        this.placeHolder = '请输入表单名称';
        var inputele = this.$el.getElementsByTagName('input');
        setTimeout(function () {
          inputele[0].focus();
          console.log(inputele[0]);
        }, 0);
      },
      save: function () {
        var CurrentNode = this.curNode;
        var oidv = CurrentNode.original.oid;
        var obj = {};

        if (this.jstree == 'basedata') {
          alert('basedata node id: ' + this.nodeId);
        } else if (this.jstree == 'user-dept-tree') {
          alert('user-dept-tree node id: ' + this.nodeId);
        } else {
          if (this.isAddReport) {
            obj.packId = oidv;
            obj.name = this.btName;
            var retD = yddser.addOrUpdateForm(obj);
            cn.yddToJstree(retD.data);
            if (cm.dataOk(retD)) {
              console.log(CurrentNode);
              console.log(retD.data);
              $('.cube_dimension_tree').jstree(true).create_node(CurrentNode, retD.data, 'first');
              $('#workspace_toolbar_panel').show();
              $('#chrome-tabs-panel').show();
              $('#rightBox').css('background', 'none');
              cn.openForm(null, null, retD.data);
            }
          }
          else if (this.isPackage) {
            obj.oid = oidv;
            obj.name = this.btName;
            var retD = yddser.addOrUpdatePack(obj);
            if (cm.dataOk(retD)) {
              CurrentNode.original.name = this.btName;
              //noinspection JSUnresolvedFunction
              $('.cube_dimension_tree').jstree(true).rename_node(CurrentNode, this.btName);
            }
          }
          else {
            obj.oid = oidv;
            obj.name = this.btName;
            var retD = yddser.addOrUpdateForm(obj);
            if (cm.dataOk(retD)) {
              CurrentNode.original.name = this.btName;
              $('.cube_dimension_tree').jstree(true).rename_node(CurrentNode, this.btName);
            }
          }
        }
        this.btName = '';
        this.$el.style.display = 'none';
        $('#' + this.nodeId + ' > div').find('.am-icon-cog').removeClass('show');
      },
      deleteNode: function () {
        var CurrentNode = this.curNode;
        if (this.jstree == 'basedata') {
          cm.myAlertFunc('确定要删除 "' + this.curNode.original.groupName + '" 基础数据吗', this.curNode.original, function (inData) {
            var ret = yddser.deleteGroupBaseData(inData.groupName);
            if (cm.dataOk(ret)) {
              var treeObj = $('#jstree-basedata').jstree(true);
              var selNode = treeObj.get_selected(true);
              var nextNode = treeObj.get_next_dom(CurrentNode);
              treeObj.delete_node(CurrentNode);
              if (selNode[0] != CurrentNode) {
                treeObj.select_node(nextNode);
              }
              //baseDataPanel.$method.setPanelData(nextNode.original.groupName, nextNode.original.groupName.dataShowType);
            }
          });
        } else if (this.jstree == 'user-dept-tree') {
          alert('user-dept-tree delete');
        } else {
          cm.myAlertFunc('确定要删除 "' + this.curNode.original.name + '" 这条记录吗？', this.curNode, function (inData) {
            var selNode = $('.cube_dimension_tree').jstree(true).get_selected(true);
            var ret = null;
            if (cm.strStartWith(inData.original.oid, 'fm')) {
              ret = yddser.delForm(inData.original.oid);
            } else if (cm.strStartWith(inData.original.oid, 'pk')) {
              ret = yddser.delPack(inData.original.oid);
            }
            if (cm.dataOk(ret)) {
              $('.cube_dimension_tree').jstree(true).delete_node(inData);
            }
          });
        }
      },
      cancel: function () {
        this.$el.style.display = 'none';
        $('#' + this.nodeId + ' > div').find('.am-icon-cog').removeClass('show');
      }
    },
    computed: {
      isPackage: function () {
        return this.nodeId.slice(0, 2) == 'pk';
      }
    }
  });

  var authCom = new Vue({
    el: '#edit-auth',
    data: {
      nodeId: '',
      view: false,
      fillIn: false,
    },
    methods: {
      save: function () {
        var deptUserId = getUserRightDeptUserId();
        var packFormId = this.nodeId;

        var curModify = {};
        curModify.data={};
        curModify.data[deptUserId]={};
        curModify.data[deptUserId][packFormId]={};
        curModify.data[deptUserId][packFormId].view = this.view;
        curModify.data[deptUserId][packFormId].edit = this.fillIn;
        curModify.data[deptUserId][packFormId].deptUserId = deptUserId;
        curModify.data[deptUserId][packFormId].packFormId = packFormId;

        var ret = yddser.resetRightByUserForm(curModify.data);
        if (cm.dataNotOk(ret)) {
          cn.showFailedDlg(ret.msg);
        }
      },
      cancel: function () {
      }
    }
  });

  var addDataSet = new Vue({
    el: '#add-data-set',
    data: {
      tabs: []
    },
    methods: {
      newField: function (index) {
        this.tabs[index].columns.push({
          fieldName: 'new Name',
          fieldType: 3,
          fieldLength: 255,
          cellPos: 'null'
        });
      },
      save: function () {
        var formData = cn.getCurTabForm();
        if (formData.cellPlus.formObj.tableArr == null) {
          formData.cellPlus.formObj.tableArr = [];
        }
        formData.cellPlus.formObj.tableArr.push(this.tabs[0]);
      },
      cancel: function () {
      }
    }
  });

  var viewDateSet = new Vue({
    el: '#view-data-set',
    data: {
      tabs: []
    },
    methods: {
      search: function (index) {
        for (var i = 0; i < this.tabs.length; i++) {
          if (i == index) {
            for (var j = 0; j < this.tabs[i].columns.length; j++) {
              if (this.tabs[i].columns[j].fieldName.toLowerCase().indexOf(this.tabs[i].keywords.toLowerCase()) == -1) {
                this.tabs[i].columns[j].show = false;
              } else {
                this.tabs[i].columns[j].show = true;
              }
            }
          }
        }
      },
      fixPosition: function (pos) {
        var x = pos.charAt(0).charCodeAt(0) - 'A'.charCodeAt(0);
        var y = pos.charAt(1);
        y = parseInt(y);

        if (cn.getCurCellPlus() != null) {
          var sheet = cn.getCurCellPlus().rawO.sheets[0];
          sheet.setActiveCell(y, x);
          sheet.showCell(y, x, GC.Spread.Sheets.VerticalPosition.center, GC.Spread.Sheets.HorizontalPosition.center);
        }
      },
      deleteDateSet: function (index) {
        var count = 0;
        for (var i = 0; i < this.tabs[index].length; i++) {
          if (this.tabs[index][i].selected) {
            count++;
          }
        }
        $('#view-data-set').modal('close');
        $('#delete-confirm .am-modal-hd').text('选中个数: ' + count);
        $('#delete-confirm .am-modal-bd').text('你，确定要删除这些记录吗？');
        $('#delete-confirm').modal({
          relatedTarget: this,
          onCancel: function (e) {
            alert('不删除');
          },
          onConfirm: function (e) {
            alert('确定删除');
          }
        });
      },
      save: function () {
        var formData = cn.getCurTabForm();
        formData.cellPlus.formObj.tableArr = this.tabs;
      },
      cancel: function () {

      }
    }
  });
  $('#new-employee').click(function () {
    var CurrentNode = $('#user-dept-tree').jstree(true).get_selected(true);
    if (CurrentNode != null) {
      newEmployee.$data.user.dept = CurrentNode[0].original.id;
      newEmployee.$data.user.deptName = CurrentNode[0].original.deptName;
    }
    $('#new-employee-panel').modal({
      relatedTarget: this,
      closeOnConfirm: false
    });
  });

  $('#tab-user-authority').click(function () {

  });


  var newEmployee = new Vue({
    el: '#new-employee-panel',
    data: {
      user: {
        userName: '',
        oid: '',
        gender: 1,
        dept: '',
        deptName: '',
        cellPhone: '',
        email: '',
        pwd: '',
        userType: 1
      }

    },
    methods: {
      cancel: function () {
        this.user.userName = '';
        this.user.oid = '';
        this.user.deptName = '';
        this.user.email = '';
        this.user.pwd = '';
        $('#new-employee-panel').modal('close');
      },
      prevent: function () {
        this.valid = true;
      },
      save: function () {
        $('#validFrom').click();
        if (this.valid) {
          var isAdd = false;
          if (this.user.oid == null || this.user.oid == "") {
            isAdd = true;
            var ret = yddser.getNewId("ur");
            if (cm.dataOk(ret)) {
              this.user.oid = ret.data;
            }
            else {
              cn.showFailedDlg(ret.msg);
              return;
            }
          }

          ret = yddser.addOrUpdateUser(this.user);
          if (cm.dataOk(ret)) {
            if (isAdd) {
              var CurrentNode = $('#user-dept-tree').jstree(true).get_selected(true);
              if (CurrentNode != null && CurrentNode[0].original.oid == this.user.dept) {
                this.user.show=true;
                userPanel.$data.gridData.push(cm.cloneObj2(this.user));
              }
            }
          }
          else {
            cn.showFailedDlg(ret.msg);
            this.user.oid = '';
            return;
          }
          this.user.userName = '';
          this.user.oid = '';
          this.user.deptName = '';
          this.user.email = '';
          this.user.pwd = '';
          $('#new-employee-panel').modal('close');
        } else {
          console.log('验证不通过');
        }
      },
      getDept: function () {
        showDeptUserModal(this.user, function (inData, selDepts, selUsers) {
          for (var i = 0; i < selDepts.length; i++) {
            if (selDepts[i].name != null) {
              newEmployee.$data.user.deptName = selDepts[i].name;
              newEmployee.$data.user.dept = selDepts[i].id;
            }
          }

        }, "department");

      }
    }
  });

  var userAuthority = new Vue({
    el: '#vue-user-authority',
    data: {
      user: {
        isDept: 1,
        userName: ''
      },
      keywords: '',
      showSearch: false,
      searchTo: '',
      curRightInfo: {view: false, edit: false, rightFrom: "self"},
      curModify: {data: {}, modify: false, curNode: ''}
    },
    methods: {
      showSearchInput: function (jstreeId) {
        if (this.showSearch) {
          this.showSearch = false;
          this.keywords = '';
          $('#' + jstreeId).jstree(true).clear_search();
        } else {
          this.showSearch = true;
        }
      },
      searchReports: function (jstreeId) {
        if (this.searchTo) {
          clearTimeout(this.searchTo);
        }
        var keywords = this.keywords;
        this.searchTo = setTimeout(function () {
          $('#' + jstreeId).jstree(true).search(keywords);
        }, 500);
      },
      clearSearch: function (jstreeId) {
        this.keywords = '';
        $('#' + jstreeId).jstree(true).clear_search();
      },
      addRole: function () {
        alert('addRole');
      }
    }
  });

  var disalbeEventUserReport = false;

  function getUserRightDeptUserId() {
    var deptSel = $('#userright-dept-tree').jstree(true).get_selected();
    var jsTreea = $('#userright-user-tree').jstree(true);
    var userSel = null;
    if (jsTreea) {
      userSel = jsTreea.get_selected();
    }

    var deptUserId = deptSel[0]
    if (!cm.isEmptyArr(userSel)) {
      deptUserId = userSel[0]
    }
    return deptUserId;
  }

  var dtpTree = new Vue({
    el: '#department-serach-bar',
    data: {
      selectNode: '维度',
      showSearch: false,
      keywords: '',
      searchTo: ''
    },
    methods: {
      refresh: function () {
        alert('userright-dept-tree refresh');
      },
      showSearchInput: function() {
        if(this.showSearch) {
          this.showSearch = false;
          this.keywords = '';
          $('#userright-dept-tree').jstree(true).clear_search();
        } else {
          this.showSearch = true;
        }
      },
      search: function() {
        if(this.searchTo) {
          clearTimeout(this.searchTo);
        }
        var keywords = this.keywords;
        this.searchTo = setTimeout(function() {
          $('#userright-dept-tree').jstree(true).search(keywords);
        }, 500);
      },
      clearSearch: function() {
        this.keywords = '';
        $('#userright-dept-tree').jstree(true).clear_search();
      },
    }
  })
  var userTree = new Vue({
    el: '#user-serach-bar',
    data: {
      selectNode: '维度',
      showSearch: false,
      keywords: '',
      searchTo: ''
    },
    methods: {
      refresh: function () {
        alert('userright-user-tree refresh');
      },
      showSearchInput: function() {
        if(this.showSearch) {
          this.showSearch = false;
          this.keywords = '';
          $('#userright-user-tree').jstree(true).clear_search();
        } else {
          this.showSearch = true;
        }
      },
      search: function() {
        if(this.searchTo) {
          clearTimeout(this.searchTo);
        }
        var keywords = this.keywords;
        this.searchTo = setTimeout(function() {
          $('#userright-user-tree').jstree(true).search(keywords);
        }, 500);
      },
      clearSearch: function() {
        this.keywords = '';
        $('#userright-user-tree').jstree(true).clear_search();
      },
    }
  })

  $('#userright-dept-tree').on('select_node.jstree', function (node, selected) {
    dtpTree.$data.selectNode = selected.node.text;
    if (userAuthority.$data.curModify.curNode == selected.node.original.oid) {
      return;
    }
    if (userAuthority.$data.curModify.modify) {
      $('#my-alert .am-modal-bd').text('发现未保存修改, 请保存或取消');
      $('#my-alert').modal();
      $('#userright-user-tree').jstree(true).select_node(userAuthority.$data.curModify.curNode);
      return;
    }
    userAuthority.$data.curModify.curNode = selected.node.original.oid;
    var data = yddser.getRightPackFormSetting(selected.node.original.oid).data;
    $('#userright-pack-tree').jstree(true).deselect_all();
    $('#userright-pack-tree').jstree(true).uncheck_all();
    $('#userright-pack-tree').jstree(true).check_node(data);

    $('#userright-dept-tree').jstree(true).uncheck_all();
    if ($('#userright-user-tree').jstree(true)) {
      $('#userright-user-tree').jstree(true).uncheck_all();
    }
    $('#userright-dept-tree').jstree(true).check_node(selected.node.original.oid);

    data = yddser.getRightAllByUserForm(selected.node.original.oid).data;
    userAuthority.$data.curModify.data = data;
    userAuthority.$data.user = {};
    userAuthority.$data.user.isDept = 1;
    var ret = yddser.getDept(selected.node.original.oid, false);
    if (cm.dataOk(ret)) {
      userAuthority.$data.user.userName = ret.data[0].deptName;
    }
    loadUserRightUserTree(selected.node.original.oid);
  }).jstree({
    'core': {
      'multiple': false,
      'check_callback': true,
      'data': yddser.getDept("all", true).data
    },
    'checkbox': {
      three_state: false,
      whole_node: false,
      tie_selection: false,
    },
    'search': {
      show_only_matches: true
    },
    'types': {
      'default': {
        'icon': '../main/img/department.png',
        'valid_children': ['default', 'department']
      },
      'department': {
        'icon': '../main/img/department.png',
        'valid_children': ['default', 'department']
      }
    },
    'plugins': ['checkbox', 'wholerow', 'search', 'types']
  });


  function loadUserRightUserTree(deptId) {
    if ($('#userright-user-tree').jstree(true)) {
      $('#userright-user-tree').jstree(true).destroy();
    }
    $('#userright-user-tree').jstree({
      'core': {
        'multiple': false,
        'check_callback': true,
        'data': yddser.getDeptUser(deptId, true).data
      },
      'checkbox': {
        three_state: false,
        whole_node: false,
        tie_selection: false,
      },
      'search': {
        show_only_matches: true
      },
      'types': {
        'default': {'icon': '../main/img/user.png', 'valid_children': ['default', 'user']},
        'user': {'icon': '../main/img/user.png', 'valid_children': ['default', 'user']}
      },
      'plugins': ['checkbox', 'wholerow', 'search', 'types']
    }).on('select_node.jstree', function (node, selected) {
      userTree.$data.selectNode = selected.node.text;
      if (userAuthority.$data.curModify.curNode == selected.node.original.oid) {
        return;
      }
      if (userAuthority.$data.curModify.modify) {
        $('#my-alert .am-modal-bd').text('发现未保存修改, 请保存或取消');
        $('#my-alert').modal();
        $('#userright-user-tree').jstree(true).select_node(userAuthority.$data.curModify.curNode);
        return;
      }

      userAuthority.$data.curModify.curNode = selected.node.original.oid;
      var data = yddser.getRightPackFormSetting(selected.node.original.oid).data;
      $('#userright-pack-tree').jstree(true).deselect_all();
      $('#userright-pack-tree').jstree(true).uncheck_all();
      $('#userright-pack-tree').jstree(true).check_node(data);

      $('#userright-dept-tree').jstree(true).uncheck_all();
      $('#userright-user-tree').jstree(true).uncheck_all();
      $('#userright-user-tree').jstree(true).check_node(selected.node.original.oid);
      data = yddser.getRightAllByUserForm(selected.node.original.oid).data;
      var ret = yddser.getUser2(selected.node.original.oid, -1, 1);
      if (cm.dataOk(ret)) {
        userAuthority.$data.user = cm.dataVal(ret)[0];
      }
      userAuthority.$data.user.isDept = 0;
      userAuthority.$data.curModify.data = data;

    });
  }

  $('#change-password').click(function () {
    event.stopPropagation();
    $('#change-pwd').modal({
      closeOnConfirm: false
    });
  })

  new Vue({
    el: '#change-pwd',
    data: {
      oldPwd: '',
      newPwd: '',
      confirmNewPwd: ''
    },
    methods: {
      save: function () {
        if (this.oldPwd == null || this.oldPwd.trim() == '') {
          alert('请输入原密码.');
        } else if (this.newPwd == null || this.newPwd.trim() == '') {
          alert('请输入新密码.');
        } else if (this.confirmNewPwd == null || this.confirmNewPwd.trim() == '') {
          alert('请输入确认新密码.');
        } else if (this.newPwd != this.confirmNewPwd) {
          alert('两次密码不一致.')
        } else {
          var ret = yddser.changePwd(user.data.oid, this.oldPwd, this.newPwd);
          if (cm.dataNotOk(ret)) {
            cn.showFailedDlg(ret.msg);
          }
          else {
            this.oldPwd = this.newPwd = "";
            $('#change-pwd').modal('close');
          }
        }
      }
    }
  });

  // var tempUiSize = {};
  // $('#J-workspace-filter').draggable({
  //     containment: "parent",
  //     handle: ".filter-bar",
  //     stop: function (event, ui) {
  //         $(event.target).width(tempUiSize.width);
  //         $(event.target).height(tempUiSize.height);
  //     }
  // }).resizable({
  //     handles: "n, e, s, w, ne, se, sw, nw",
  //     containment: "parent",
  //     autoHide: true,
  //     stop: function (event, ui) {
  //         if (ui.size.width < 300) {
  //             ui.size.width = 300;
  //         }
  //         if (ui.size.height < 400) {
  //             ui.size.height = 400;
  //         }
  //         tempUiSize = ui.size;
  //     }
  // });

  // $('#J-filter-expand').click(function () {
  //     if ($('#J-workspace-filter').hasClass('fold')) {
  //         $('#J-workspace-filter').removeClass('fold');
  //         $('.filter-content').show();
  //         $('#J-workspace-filter > .ui-resizable-handle').show();
  //         var newLeft = $('#J-workspace-filter').offset().left - (tempUiSize.width - 300);
  //         if (newLeft < 0) {
  //             newLeft = 0;
  //         }
  //         $('#J-workspace-filter').css('left', newLeft);
  //         $('#J-workspace-filter').resizable('enable');

  //     } else {
  //         $('#J-workspace-filter').resizable('disable');
  //         $('#J-workspace-filter').removeClass('ui-state-disabled');
  //         $('#J-workspace-filter > .ui-resizable-handle').hide();
  //         $('.filter-content').hide();

  //         var newLeft = $('#J-workspace-filter').offset().left + (tempUiSize.width - 300);
  //         if (newLeft < 0) {
  //             newLeft = 0;
  //         }
  //         $('#J-workspace-filter').addClass('fold').css('left', newLeft);
  //     }
  // });


  (function ($) {
    $.fn.extend({
      insertContent: function (myValue, t) {
        var $t = $(this)[0];
        if (document.selection) { // ie
          this.focus();
          var sel = document.selection.createRange();
          sel.text = myValue;
          this.focus();
          sel.moveStart('character', -l);
          var wee = sel.text.length;
          if (arguments.length == 2) {
            var l = $t.value.length;
            sel.moveEnd("character", wee + t);
            t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length);
            sel.select();
          }
        } else if ($t.selectionStart
          || $t.selectionStart == '0') {
          var startPos = $t.selectionStart;
          var endPos = $t.selectionEnd;
          var scrollTop = $t.scrollTop;
          $t.value = $t.value.substring(0, startPos)
            + myValue
            + $t.value.substring(endPos, $t.value.length);
          this.focus();
          $t.selectionStart = startPos + myValue.length;
          $t.selectionEnd = startPos + myValue.length;
          $t.scrollTop = scrollTop;
          if (arguments.length == 2) {
            $t.setSelectionRange(startPos - t,
              $t.selectionEnd + t);
            this.focus();
          }
        } else {
          this.value += myValue;
          this.focus();
        }
      }
    })
  })(jQuery);

  Vue.component('search-bar', {
    template: '#search-template',
    props: {
      jstree: String,
      showResizeBar: Boolean,
      area: String
    },
    data: function () {
      return {
        showSearch: false,
        keywords: '',
        searchTo: ''
      }
    },
    methods: {
      resizeBar: function() {
          var disX = event.clientX;
          var area = this.area;
          var w = $(window).width();
          document.onmousemove = function (e) {
              if(e.clientX > 260 && e.clientX < 462) {
                  var lw = e.clientX - 60;
                  $('#' + area + ' .left-side').width(lw);
                  $('#' + area + ' .right-side').width(w - e.clientX - 1).css('left', lw);
              }
          };
          document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
          };
      },
      showSearchInput: function () {
        if (this.showSearch) {
          this.showSearch = false;
          this.keywords = '';
          $('#' + this.jstree).jstree(true).clear_search();
        } else {
          this.showSearch = true;
        }
      },
      search: function () {
        if (this.searchTo) {
          clearTimeout(this.searchTo);
        }
        var keywords = this.keywords;
        var jstreeId = this.jstree;
        this.searchTo = setTimeout(function () {
          $('#' + jstreeId).jstree(true).search(keywords);
        }, 500);
      },
      clearSearch: function () {
        this.keywords = '';
        $('#' + this.jstree).jstree(true).clear_search();
      },
    }
  });

  function addSettings(root, ele, setOptions) {
      if($('#' + ele.node.id + ' > div').find('.am-icon-cog').length == 0) {
          var settings = $('<i class="am-icon-cog"></i>');
          var isEnter = false;
          settings.on('click', function(e) {
              e.stopPropagation();

              if($(this).hasClass('show')) {
                  $(this).removeClass('show');
                  $('#business-tooltips').hide();
              } else {
                  $(root).find('.am-icon-cog.show').each(function() {
                      $(this).removeClass('show');
                  });
                  $(this).addClass('show');

                  setOptions();

                  var offset = $(this).offset();
                  $('#business-tooltips').css({'left': offset.left - 10, 'top': offset.top + 18}).show();

                  var self = this;

                  $(document).bind('mousedown.business-tooltips', function() {
                      var el = event.target;
                      var btips = $('#business-tooltips')[0];

                      while (true) {
                          if (el == self || el == btips) {
                              return true;
                          } else if (el == document) {
                              $('#business-tooltips').hide();
                              $(self).removeClass('show');
                              btPop.$data.showBtns = true;
                              $(document).unbind('mousedown.business-tooltips');
                              return false;
                          } else {
                              el = $(el).parent()[0];
                          }
                      }
                  });
              }
          });
          $('#' + ele.node.id + ' > div').append(settings);
      }
  }

  Vue.component('user-grid', {
    template: '#grid-template',
    props: {
      data: Array,
      columns: Array,
      sort: Boolean
    },
    data: function () {
      var sortOrders = {};
      this.columns.forEach(function (key) {
        sortOrders[key.name] = 1
      });
      return {
        sortKey: '',
        sortOrders: sortOrders,
        userIds: []
      }
    },
    methods: {
      sortBy: function (key) {
        if(key != '') {
          this.sortKey = key
          this.sortOrders[key] = this.sortOrders[key] * -1
        }
      },
      //修改成员信息
      edit: function (u) {
        if (u.oid.indexOf("bsd") >= 0) {
          basedata_modal.$data.data = u;
          basedata_modal.$data.data.groupName = u.groupName;
          basedata_modal.$data.data.dataShowType = u.dataShowType;
          basedata_modal.showModal("修改数据项", 2, function (editData) {
            editData.updateTime = cm.dtToLong();
            editData.updateTimeStr = cm.dtToLYMDMS(editData.updateTime);
            var ret = yddser.addOrUpdBaseDataItem(editData);
            if (cm.dataNotOk(ret)) {
              cn.showFailedDlg(ret.msg);
              return;
            }
          });
          return;
        }
        newEmployee.$data.user = u;
        var CurrentNode = $('#user-dept-tree').jstree(true).get_selected(true);
        if (CurrentNode != null) {
          newEmployee.$data.user.dept = CurrentNode[0].original.id;
          newEmployee.$data.user.deptName = CurrentNode[0].original.deptName;
        }
        $('#new-employee-panel').modal({
          relatedTarget: this,
          closeOnConfirm: false
        });
      },
      deleteItem: function (u) {
        for (var i = this.data.length - 1; i >= 0; i--) {
          if (this.data[i].oid == u.oid) {
            var ret;
            if (u.oid.indexOf("bsd") >= 0) {
              ret = yddser.deleteBaseDataItem(u.oid);
            }
            else {
              ret = yddser.delUser(u.oid);
            }
            if (cm.dataOk(ret)) {
              this.data.splice(i, 1);
            }
            break;
          }
        }
      },
      deleteSelected: function () {
        // this.$parent
        for (var i = 0; i < this.userIds.length; i++) {
          for (var j = 0; j < this.data.length; j++) {
            if (this.data[j].oid == this.userIds[i]) {
              this.data.splice(j, 1);
              break;
            }
          }
        }
      }
    },
    computed: {
      allCheck: {
        get: function () {
          if (this.$data.userIds.length == this.data.length) {
            return true;
          }
          return false;
        },
        set: function (newValue) {
          this.$data.userIds = [];
          if (newValue) {
            for (var i = 0; i < this.data.length; i++) {
              this.$data.userIds.push(this.data[i].oid);
            }
          }
        }
      }
    }
  });
});